vk_rasterizer.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522
  1. // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <array>
  5. #include <memory>
  6. #include <mutex>
  7. #include "video_core/renderer_vulkan/renderer_vulkan.h"
  8. #include "common/assert.h"
  9. #include "common/logging/log.h"
  10. #include "common/microprofile.h"
  11. #include "common/scope_exit.h"
  12. #include "common/settings.h"
  13. #include "video_core/control/channel_state.h"
  14. #include "video_core/engines/draw_manager.h"
  15. #include "video_core/engines/kepler_compute.h"
  16. #include "video_core/engines/maxwell_3d.h"
  17. #include "video_core/renderer_vulkan/blit_image.h"
  18. #include "video_core/renderer_vulkan/fixed_pipeline_state.h"
  19. #include "video_core/renderer_vulkan/maxwell_to_vk.h"
  20. #include "video_core/renderer_vulkan/vk_buffer_cache.h"
  21. #include "video_core/renderer_vulkan/vk_compute_pipeline.h"
  22. #include "video_core/renderer_vulkan/vk_descriptor_pool.h"
  23. #include "video_core/renderer_vulkan/vk_pipeline_cache.h"
  24. #include "video_core/renderer_vulkan/vk_query_cache.h"
  25. #include "video_core/renderer_vulkan/vk_rasterizer.h"
  26. #include "video_core/renderer_vulkan/vk_scheduler.h"
  27. #include "video_core/renderer_vulkan/vk_staging_buffer_pool.h"
  28. #include "video_core/renderer_vulkan/vk_state_tracker.h"
  29. #include "video_core/renderer_vulkan/vk_texture_cache.h"
  30. #include "video_core/renderer_vulkan/vk_update_descriptor.h"
  31. #include "video_core/shader_cache.h"
  32. #include "video_core/texture_cache/texture_cache_base.h"
  33. #include "video_core/vulkan_common/vulkan_device.h"
  34. #include "video_core/vulkan_common/vulkan_wrapper.h"
  35. namespace Vulkan {
  36. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  37. using MaxwellDrawState = Tegra::Engines::DrawManager::State;
  38. using VideoCommon::ImageViewId;
  39. using VideoCommon::ImageViewType;
  40. MICROPROFILE_DEFINE(Vulkan_WaitForWorker, "Vulkan", "Wait for worker", MP_RGB(255, 192, 192));
  41. MICROPROFILE_DEFINE(Vulkan_Drawing, "Vulkan", "Record drawing", MP_RGB(192, 128, 128));
  42. MICROPROFILE_DEFINE(Vulkan_Compute, "Vulkan", "Record compute", MP_RGB(192, 128, 128));
  43. MICROPROFILE_DEFINE(Vulkan_Clearing, "Vulkan", "Record clearing", MP_RGB(192, 128, 128));
  44. MICROPROFILE_DEFINE(Vulkan_PipelineCache, "Vulkan", "Pipeline cache", MP_RGB(192, 128, 128));
  45. namespace {
  46. struct DrawParams {
  47. u32 base_instance;
  48. u32 num_instances;
  49. u32 base_vertex;
  50. u32 num_vertices;
  51. u32 first_index;
  52. bool is_indexed;
  53. };
  54. VkViewport GetViewportState(const Device& device, const Maxwell& regs, size_t index, float scale) {
  55. const auto& src = regs.viewport_transform[index];
  56. const auto conv = [scale](float value) {
  57. float new_value = value * scale;
  58. if (scale < 1.0f) {
  59. const bool sign = std::signbit(value);
  60. new_value = std::round(std::abs(new_value));
  61. new_value = sign ? -new_value : new_value;
  62. }
  63. return new_value;
  64. };
  65. const float x = conv(src.translate_x - src.scale_x);
  66. const float width = conv(src.scale_x * 2.0f);
  67. float y = conv(src.translate_y - src.scale_y);
  68. float height = conv(src.scale_y * 2.0f);
  69. bool y_negate = regs.window_origin.mode != Maxwell::WindowOrigin::Mode::UpperLeft;
  70. if (!device.IsNvViewportSwizzleSupported()) {
  71. y_negate = y_negate != (src.swizzle.y == Maxwell::ViewportSwizzle::NegativeY);
  72. }
  73. if (y_negate) {
  74. y += height;
  75. height = -height;
  76. }
  77. const float reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne ? 1.0f : 0.0f;
  78. VkViewport viewport{
  79. .x = x,
  80. .y = y,
  81. .width = width != 0.0f ? width : 1.0f,
  82. .height = height != 0.0f ? height : 1.0f,
  83. .minDepth = src.translate_z - src.scale_z * reduce_z,
  84. .maxDepth = src.translate_z + src.scale_z,
  85. };
  86. if (!device.IsExtDepthRangeUnrestrictedSupported()) {
  87. viewport.minDepth = std::clamp(viewport.minDepth, 0.0f, 1.0f);
  88. viewport.maxDepth = std::clamp(viewport.maxDepth, 0.0f, 1.0f);
  89. }
  90. return viewport;
  91. }
  92. VkRect2D GetScissorState(const Maxwell& regs, size_t index, u32 up_scale = 1, u32 down_shift = 0) {
  93. const auto& src = regs.scissor_test[index];
  94. VkRect2D scissor;
  95. const auto scale_up = [&](s32 value) -> s32 {
  96. if (value == 0) {
  97. return 0U;
  98. }
  99. const s32 upset = value * up_scale;
  100. s32 acumm = 0;
  101. if ((up_scale >> down_shift) == 0) {
  102. acumm = upset % 2;
  103. }
  104. const s32 converted_value = (value * up_scale) >> down_shift;
  105. return value < 0 ? std::min<s32>(converted_value - acumm, -1)
  106. : std::max<s32>(converted_value + acumm, 1);
  107. };
  108. if (src.enable) {
  109. scissor.offset.x = scale_up(static_cast<s32>(src.min_x));
  110. scissor.offset.y = scale_up(static_cast<s32>(src.min_y));
  111. scissor.extent.width = scale_up(src.max_x - src.min_x);
  112. scissor.extent.height = scale_up(src.max_y - src.min_y);
  113. } else {
  114. scissor.offset.x = 0;
  115. scissor.offset.y = 0;
  116. scissor.extent.width = std::numeric_limits<s32>::max();
  117. scissor.extent.height = std::numeric_limits<s32>::max();
  118. }
  119. return scissor;
  120. }
  121. DrawParams MakeDrawParams(const MaxwellDrawState& draw_state, u32 num_instances, bool is_indexed) {
  122. DrawParams params{
  123. .base_instance = draw_state.base_instance,
  124. .num_instances = num_instances,
  125. .base_vertex = is_indexed ? draw_state.base_index : draw_state.vertex_buffer.first,
  126. .num_vertices = is_indexed ? draw_state.index_buffer.count : draw_state.vertex_buffer.count,
  127. .first_index = is_indexed ? draw_state.index_buffer.first : 0,
  128. .is_indexed = is_indexed,
  129. };
  130. // 6 triangle vertices per quad, base vertex is part of the index
  131. // See BindQuadIndexBuffer for more details
  132. if (draw_state.topology == Maxwell::PrimitiveTopology::Quads) {
  133. params.num_vertices = (params.num_vertices / 4) * 6;
  134. params.base_vertex = 0;
  135. params.is_indexed = true;
  136. } else if (draw_state.topology == Maxwell::PrimitiveTopology::QuadStrip) {
  137. params.num_vertices = (params.num_vertices - 2) / 2 * 6;
  138. params.base_vertex = 0;
  139. params.is_indexed = true;
  140. }
  141. return params;
  142. }
  143. } // Anonymous namespace
  144. RasterizerVulkan::RasterizerVulkan(Core::Frontend::EmuWindow& emu_window_, Tegra::GPU& gpu_,
  145. Core::Memory::Memory& cpu_memory_, ScreenInfo& screen_info_,
  146. const Device& device_, MemoryAllocator& memory_allocator_,
  147. StateTracker& state_tracker_, Scheduler& scheduler_)
  148. : RasterizerAccelerated{cpu_memory_}, gpu{gpu_}, screen_info{screen_info_}, device{device_},
  149. memory_allocator{memory_allocator_}, state_tracker{state_tracker_}, scheduler{scheduler_},
  150. staging_pool(device, memory_allocator, scheduler), descriptor_pool(device, scheduler),
  151. guest_descriptor_queue(device, scheduler), compute_pass_descriptor_queue(device, scheduler),
  152. blit_image(device, scheduler, state_tracker, descriptor_pool), render_pass_cache(device),
  153. texture_cache_runtime{
  154. device, scheduler, memory_allocator, staging_pool,
  155. blit_image, render_pass_cache, descriptor_pool, compute_pass_descriptor_queue},
  156. texture_cache(texture_cache_runtime, *this),
  157. buffer_cache_runtime(device, memory_allocator, scheduler, staging_pool,
  158. guest_descriptor_queue, compute_pass_descriptor_queue, descriptor_pool),
  159. buffer_cache(*this, cpu_memory_, buffer_cache_runtime),
  160. query_cache_runtime(this, cpu_memory_, buffer_cache, device, memory_allocator, scheduler,
  161. staging_pool, compute_pass_descriptor_queue, descriptor_pool),
  162. query_cache(gpu, *this, cpu_memory_, query_cache_runtime),
  163. pipeline_cache(*this, device, scheduler, descriptor_pool, guest_descriptor_queue,
  164. render_pass_cache, buffer_cache, texture_cache, gpu.ShaderNotify()),
  165. accelerate_dma(buffer_cache, texture_cache, scheduler),
  166. fence_manager(*this, gpu, texture_cache, buffer_cache, query_cache, device, scheduler),
  167. wfi_event(device.GetLogical().CreateEvent()) {
  168. scheduler.SetQueryCache(query_cache);
  169. }
  170. RasterizerVulkan::~RasterizerVulkan() = default;
  171. template <typename Func>
  172. void RasterizerVulkan::PrepareDraw(bool is_indexed, Func&& draw_func) {
  173. MICROPROFILE_SCOPE(Vulkan_Drawing);
  174. SCOPE_EXIT({ gpu.TickWork(); });
  175. FlushWork();
  176. gpu_memory->FlushCaching();
  177. query_cache.NotifySegment(true);
  178. GraphicsPipeline* const pipeline{pipeline_cache.CurrentGraphicsPipeline()};
  179. if (!pipeline) {
  180. return;
  181. }
  182. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  183. // update engine as channel may be different.
  184. pipeline->SetEngine(maxwell3d, gpu_memory);
  185. pipeline->Configure(is_indexed);
  186. UpdateDynamicStates();
  187. HandleTransformFeedback();
  188. query_cache.CounterEnable(VideoCommon::QueryType::ZPassPixelCount64,
  189. maxwell3d->regs.zpass_pixel_count_enable);
  190. draw_func();
  191. }
  192. void RasterizerVulkan::Draw(bool is_indexed, u32 instance_count) {
  193. PrepareDraw(is_indexed, [this, is_indexed, instance_count] {
  194. const auto& draw_state = maxwell3d->draw_manager->GetDrawState();
  195. const u32 num_instances{instance_count};
  196. const DrawParams draw_params{MakeDrawParams(draw_state, num_instances, is_indexed)};
  197. scheduler.Record([draw_params](vk::CommandBuffer cmdbuf) {
  198. if (draw_params.is_indexed) {
  199. cmdbuf.DrawIndexed(draw_params.num_vertices, draw_params.num_instances,
  200. draw_params.first_index, draw_params.base_vertex,
  201. draw_params.base_instance);
  202. } else {
  203. cmdbuf.Draw(draw_params.num_vertices, draw_params.num_instances,
  204. draw_params.base_vertex, draw_params.base_instance);
  205. }
  206. });
  207. });
  208. }
  209. void RasterizerVulkan::DrawIndirect() {
  210. const auto& params = maxwell3d->draw_manager->GetIndirectParams();
  211. buffer_cache.SetDrawIndirect(&params);
  212. PrepareDraw(params.is_indexed, [this, &params] {
  213. const auto indirect_buffer = buffer_cache.GetDrawIndirectBuffer();
  214. const auto& buffer = indirect_buffer.first;
  215. const auto& offset = indirect_buffer.second;
  216. if (params.is_byte_count) {
  217. scheduler.Record([buffer_obj = buffer->Handle(), offset,
  218. stride = params.stride](vk::CommandBuffer cmdbuf) {
  219. cmdbuf.DrawIndirectByteCountEXT(1, 0, buffer_obj, offset, 0,
  220. static_cast<u32>(stride));
  221. });
  222. return;
  223. }
  224. if (params.include_count) {
  225. const auto count = buffer_cache.GetDrawIndirectCount();
  226. const auto& draw_buffer = count.first;
  227. const auto& offset_base = count.second;
  228. scheduler.Record([draw_buffer_obj = draw_buffer->Handle(),
  229. buffer_obj = buffer->Handle(), offset_base, offset,
  230. params](vk::CommandBuffer cmdbuf) {
  231. if (params.is_indexed) {
  232. cmdbuf.DrawIndexedIndirectCount(
  233. buffer_obj, offset, draw_buffer_obj, offset_base,
  234. static_cast<u32>(params.max_draw_counts), static_cast<u32>(params.stride));
  235. } else {
  236. cmdbuf.DrawIndirectCount(buffer_obj, offset, draw_buffer_obj, offset_base,
  237. static_cast<u32>(params.max_draw_counts),
  238. static_cast<u32>(params.stride));
  239. }
  240. });
  241. return;
  242. }
  243. scheduler.Record([buffer_obj = buffer->Handle(), offset, params](vk::CommandBuffer cmdbuf) {
  244. if (params.is_indexed) {
  245. cmdbuf.DrawIndexedIndirect(buffer_obj, offset,
  246. static_cast<u32>(params.max_draw_counts),
  247. static_cast<u32>(params.stride));
  248. } else {
  249. cmdbuf.DrawIndirect(buffer_obj, offset, static_cast<u32>(params.max_draw_counts),
  250. static_cast<u32>(params.stride));
  251. }
  252. });
  253. });
  254. buffer_cache.SetDrawIndirect(nullptr);
  255. }
  256. void RasterizerVulkan::DrawTexture() {
  257. MICROPROFILE_SCOPE(Vulkan_Drawing);
  258. SCOPE_EXIT({ gpu.TickWork(); });
  259. FlushWork();
  260. query_cache.NotifySegment(true);
  261. texture_cache.SynchronizeGraphicsDescriptors();
  262. texture_cache.UpdateRenderTargets(false);
  263. UpdateDynamicStates();
  264. query_cache.CounterEnable(VideoCommon::QueryType::ZPassPixelCount64,
  265. maxwell3d->regs.zpass_pixel_count_enable);
  266. const auto& draw_texture_state = maxwell3d->draw_manager->GetDrawTextureState();
  267. const auto& sampler = texture_cache.GetGraphicsSampler(draw_texture_state.src_sampler);
  268. const auto& texture = texture_cache.GetImageView(draw_texture_state.src_texture);
  269. Region2D dst_region = {Offset2D{.x = static_cast<s32>(draw_texture_state.dst_x0),
  270. .y = static_cast<s32>(draw_texture_state.dst_y0)},
  271. Offset2D{.x = static_cast<s32>(draw_texture_state.dst_x1),
  272. .y = static_cast<s32>(draw_texture_state.dst_y1)}};
  273. Region2D src_region = {Offset2D{.x = static_cast<s32>(draw_texture_state.src_x0),
  274. .y = static_cast<s32>(draw_texture_state.src_y0)},
  275. Offset2D{.x = static_cast<s32>(draw_texture_state.src_x1),
  276. .y = static_cast<s32>(draw_texture_state.src_y1)}};
  277. blit_image.BlitColor(texture_cache.GetFramebuffer(), texture.RenderTarget(),
  278. texture.ImageHandle(), sampler->Handle(), dst_region, src_region,
  279. texture.size);
  280. }
  281. void RasterizerVulkan::Clear(u32 layer_count) {
  282. MICROPROFILE_SCOPE(Vulkan_Clearing);
  283. FlushWork();
  284. gpu_memory->FlushCaching();
  285. query_cache.NotifySegment(true);
  286. query_cache.CounterEnable(VideoCommon::QueryType::ZPassPixelCount64,
  287. maxwell3d->regs.zpass_pixel_count_enable);
  288. auto& regs = maxwell3d->regs;
  289. const bool use_color = regs.clear_surface.R || regs.clear_surface.G || regs.clear_surface.B ||
  290. regs.clear_surface.A;
  291. const bool use_depth = regs.clear_surface.Z;
  292. const bool use_stencil = regs.clear_surface.S;
  293. if (!use_color && !use_depth && !use_stencil) {
  294. return;
  295. }
  296. std::scoped_lock lock{texture_cache.mutex};
  297. texture_cache.UpdateRenderTargets(true);
  298. const Framebuffer* const framebuffer = texture_cache.GetFramebuffer();
  299. const VkExtent2D render_area = framebuffer->RenderArea();
  300. scheduler.RequestRenderpass(framebuffer);
  301. u32 up_scale = 1;
  302. u32 down_shift = 0;
  303. if (texture_cache.IsRescaling()) {
  304. up_scale = Settings::values.resolution_info.up_scale;
  305. down_shift = Settings::values.resolution_info.down_shift;
  306. }
  307. UpdateViewportsState(regs);
  308. VkRect2D default_scissor;
  309. default_scissor.offset.x = 0;
  310. default_scissor.offset.y = 0;
  311. default_scissor.extent.width = std::numeric_limits<s32>::max();
  312. default_scissor.extent.height = std::numeric_limits<s32>::max();
  313. VkClearRect clear_rect{
  314. .rect = regs.clear_control.use_scissor ? GetScissorState(regs, 0, up_scale, down_shift)
  315. : default_scissor,
  316. .baseArrayLayer = regs.clear_surface.layer,
  317. .layerCount = layer_count,
  318. };
  319. if (clear_rect.rect.extent.width == 0 || clear_rect.rect.extent.height == 0) {
  320. return;
  321. }
  322. clear_rect.rect.extent = VkExtent2D{
  323. .width = std::min(clear_rect.rect.extent.width, render_area.width),
  324. .height = std::min(clear_rect.rect.extent.height, render_area.height),
  325. };
  326. const u32 color_attachment = regs.clear_surface.RT;
  327. if (use_color && framebuffer->HasAspectColorBit(color_attachment)) {
  328. const auto format =
  329. VideoCore::Surface::PixelFormatFromRenderTargetFormat(regs.rt[color_attachment].format);
  330. bool is_integer = IsPixelFormatInteger(format);
  331. bool is_signed = IsPixelFormatSignedInteger(format);
  332. size_t int_size = PixelComponentSizeBitsInteger(format);
  333. VkClearValue clear_value{};
  334. if (!is_integer) {
  335. std::memcpy(clear_value.color.float32, regs.clear_color.data(),
  336. regs.clear_color.size() * sizeof(f32));
  337. } else if (!is_signed) {
  338. for (size_t i = 0; i < 4; i++) {
  339. clear_value.color.uint32[i] = static_cast<u32>(
  340. static_cast<f32>(static_cast<u64>(int_size) << 1U) * regs.clear_color[i]);
  341. }
  342. } else {
  343. for (size_t i = 0; i < 4; i++) {
  344. clear_value.color.int32[i] =
  345. static_cast<s32>(static_cast<f32>(static_cast<s64>(int_size - 1) << 1) *
  346. (regs.clear_color[i] - 0.5f));
  347. }
  348. }
  349. if (regs.clear_surface.R && regs.clear_surface.G && regs.clear_surface.B &&
  350. regs.clear_surface.A) {
  351. scheduler.Record([color_attachment, clear_value, clear_rect](vk::CommandBuffer cmdbuf) {
  352. const VkClearAttachment attachment{
  353. .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  354. .colorAttachment = color_attachment,
  355. .clearValue = clear_value,
  356. };
  357. cmdbuf.ClearAttachments(attachment, clear_rect);
  358. });
  359. } else {
  360. u8 color_mask = static_cast<u8>(regs.clear_surface.R | regs.clear_surface.G << 1 |
  361. regs.clear_surface.B << 2 | regs.clear_surface.A << 3);
  362. Region2D dst_region = {
  363. Offset2D{.x = clear_rect.rect.offset.x, .y = clear_rect.rect.offset.y},
  364. Offset2D{.x = clear_rect.rect.offset.x +
  365. static_cast<s32>(clear_rect.rect.extent.width),
  366. .y = clear_rect.rect.offset.y +
  367. static_cast<s32>(clear_rect.rect.extent.height)}};
  368. blit_image.ClearColor(framebuffer, color_mask, regs.clear_color, dst_region);
  369. }
  370. }
  371. if (!use_depth && !use_stencil) {
  372. return;
  373. }
  374. VkImageAspectFlags aspect_flags = 0;
  375. if (use_depth && framebuffer->HasAspectDepthBit()) {
  376. aspect_flags |= VK_IMAGE_ASPECT_DEPTH_BIT;
  377. }
  378. if (use_stencil && framebuffer->HasAspectStencilBit()) {
  379. aspect_flags |= VK_IMAGE_ASPECT_STENCIL_BIT;
  380. }
  381. if (aspect_flags == 0) {
  382. return;
  383. }
  384. if (use_stencil && regs.stencil_front_mask != 0xFF && regs.stencil_front_mask != 0) {
  385. Region2D dst_region = {
  386. Offset2D{.x = clear_rect.rect.offset.x, .y = clear_rect.rect.offset.y},
  387. Offset2D{.x = clear_rect.rect.offset.x + static_cast<s32>(clear_rect.rect.extent.width),
  388. .y = clear_rect.rect.offset.y +
  389. static_cast<s32>(clear_rect.rect.extent.height)}};
  390. blit_image.ClearDepthStencil(framebuffer, use_depth, regs.clear_depth,
  391. static_cast<u8>(regs.stencil_front_mask), regs.clear_stencil,
  392. regs.stencil_front_func_mask, dst_region);
  393. } else {
  394. scheduler.Record([clear_depth = regs.clear_depth, clear_stencil = regs.clear_stencil,
  395. clear_rect, aspect_flags](vk::CommandBuffer cmdbuf) {
  396. VkClearAttachment attachment;
  397. attachment.aspectMask = aspect_flags;
  398. attachment.colorAttachment = 0;
  399. attachment.clearValue.depthStencil.depth = clear_depth;
  400. attachment.clearValue.depthStencil.stencil = clear_stencil;
  401. cmdbuf.ClearAttachments(attachment, clear_rect);
  402. });
  403. }
  404. }
  405. void RasterizerVulkan::DispatchCompute() {
  406. FlushWork();
  407. gpu_memory->FlushCaching();
  408. ComputePipeline* const pipeline{pipeline_cache.CurrentComputePipeline()};
  409. if (!pipeline) {
  410. return;
  411. }
  412. std::scoped_lock lock{texture_cache.mutex, buffer_cache.mutex};
  413. pipeline->Configure(*kepler_compute, *gpu_memory, scheduler, buffer_cache, texture_cache);
  414. const auto& qmd{kepler_compute->launch_description};
  415. auto indirect_address = kepler_compute->GetIndirectComputeAddress();
  416. if (indirect_address) {
  417. // DispatchIndirect
  418. static constexpr auto sync_info = VideoCommon::ObtainBufferSynchronize::FullSynchronize;
  419. const auto post_op = VideoCommon::ObtainBufferOperation::DiscardWrite;
  420. const auto [buffer, offset] =
  421. buffer_cache.ObtainBuffer(*indirect_address, 12, sync_info, post_op);
  422. scheduler.RequestOutsideRenderPassOperationContext();
  423. scheduler.Record([indirect_buffer = buffer->Handle(),
  424. indirect_offset = offset](vk::CommandBuffer cmdbuf) {
  425. cmdbuf.DispatchIndirect(indirect_buffer, indirect_offset);
  426. });
  427. return;
  428. }
  429. const std::array<u32, 3> dim{qmd.grid_dim_x, qmd.grid_dim_y, qmd.grid_dim_z};
  430. scheduler.RequestOutsideRenderPassOperationContext();
  431. scheduler.Record([dim](vk::CommandBuffer cmdbuf) { cmdbuf.Dispatch(dim[0], dim[1], dim[2]); });
  432. }
  433. void RasterizerVulkan::ResetCounter(VideoCommon::QueryType type) {
  434. query_cache.CounterReset(type);
  435. }
  436. void RasterizerVulkan::Query(GPUVAddr gpu_addr, VideoCommon::QueryType type,
  437. VideoCommon::QueryPropertiesFlags flags, u32 payload, u32 subreport) {
  438. query_cache.CounterReport(gpu_addr, type, flags, payload, subreport);
  439. }
  440. void RasterizerVulkan::BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr,
  441. u32 size) {
  442. buffer_cache.BindGraphicsUniformBuffer(stage, index, gpu_addr, size);
  443. }
  444. void Vulkan::RasterizerVulkan::DisableGraphicsUniformBuffer(size_t stage, u32 index) {
  445. buffer_cache.DisableGraphicsUniformBuffer(stage, index);
  446. }
  447. void RasterizerVulkan::FlushAll() {}
  448. void RasterizerVulkan::FlushRegion(VAddr addr, u64 size, VideoCommon::CacheType which) {
  449. if (addr == 0 || size == 0) {
  450. return;
  451. }
  452. if (True(which & VideoCommon::CacheType::TextureCache)) {
  453. std::scoped_lock lock{texture_cache.mutex};
  454. texture_cache.DownloadMemory(addr, size);
  455. }
  456. if ((True(which & VideoCommon::CacheType::BufferCache))) {
  457. std::scoped_lock lock{buffer_cache.mutex};
  458. buffer_cache.DownloadMemory(addr, size);
  459. }
  460. if ((True(which & VideoCommon::CacheType::QueryCache))) {
  461. query_cache.FlushRegion(addr, size);
  462. }
  463. }
  464. bool RasterizerVulkan::MustFlushRegion(VAddr addr, u64 size, VideoCommon::CacheType which) {
  465. if ((True(which & VideoCommon::CacheType::BufferCache))) {
  466. std::scoped_lock lock{buffer_cache.mutex};
  467. if (buffer_cache.IsRegionGpuModified(addr, size)) {
  468. return true;
  469. }
  470. }
  471. if (!Settings::IsGPULevelHigh()) {
  472. return false;
  473. }
  474. if (True(which & VideoCommon::CacheType::TextureCache)) {
  475. std::scoped_lock lock{texture_cache.mutex};
  476. return texture_cache.IsRegionGpuModified(addr, size);
  477. }
  478. return false;
  479. }
  480. VideoCore::RasterizerDownloadArea RasterizerVulkan::GetFlushArea(VAddr addr, u64 size) {
  481. {
  482. std::scoped_lock lock{texture_cache.mutex};
  483. auto area = texture_cache.GetFlushArea(addr, size);
  484. if (area) {
  485. return *area;
  486. }
  487. }
  488. VideoCore::RasterizerDownloadArea new_area{
  489. .start_address = Common::AlignDown(addr, Core::Memory::YUZU_PAGESIZE),
  490. .end_address = Common::AlignUp(addr + size, Core::Memory::YUZU_PAGESIZE),
  491. .preemtive = true,
  492. };
  493. return new_area;
  494. }
  495. void RasterizerVulkan::InvalidateRegion(VAddr addr, u64 size, VideoCommon::CacheType which) {
  496. if (addr == 0 || size == 0) {
  497. return;
  498. }
  499. if (True(which & VideoCommon::CacheType::TextureCache)) {
  500. std::scoped_lock lock{texture_cache.mutex};
  501. texture_cache.WriteMemory(addr, size);
  502. }
  503. if ((True(which & VideoCommon::CacheType::BufferCache))) {
  504. std::scoped_lock lock{buffer_cache.mutex};
  505. buffer_cache.WriteMemory(addr, size);
  506. }
  507. if ((True(which & VideoCommon::CacheType::QueryCache))) {
  508. query_cache.InvalidateRegion(addr, size);
  509. }
  510. if ((True(which & VideoCommon::CacheType::ShaderCache))) {
  511. pipeline_cache.InvalidateRegion(addr, size);
  512. }
  513. }
  514. void RasterizerVulkan::InnerInvalidation(std::span<const std::pair<VAddr, std::size_t>> sequences) {
  515. {
  516. std::scoped_lock lock{texture_cache.mutex};
  517. for (const auto& [addr, size] : sequences) {
  518. texture_cache.WriteMemory(addr, size);
  519. }
  520. }
  521. {
  522. std::scoped_lock lock{buffer_cache.mutex};
  523. for (const auto& [addr, size] : sequences) {
  524. buffer_cache.WriteMemory(addr, size);
  525. }
  526. }
  527. {
  528. for (const auto& [addr, size] : sequences) {
  529. query_cache.InvalidateRegion(addr, size);
  530. pipeline_cache.InvalidateRegion(addr, size);
  531. }
  532. }
  533. }
  534. bool RasterizerVulkan::OnCPUWrite(VAddr addr, u64 size) {
  535. if (addr == 0 || size == 0) {
  536. return false;
  537. }
  538. {
  539. std::scoped_lock lock{buffer_cache.mutex};
  540. if (buffer_cache.OnCPUWrite(addr, size)) {
  541. return true;
  542. }
  543. }
  544. {
  545. std::scoped_lock lock{texture_cache.mutex};
  546. texture_cache.WriteMemory(addr, size);
  547. }
  548. pipeline_cache.InvalidateRegion(addr, size);
  549. return false;
  550. }
  551. void RasterizerVulkan::OnCacheInvalidation(VAddr addr, u64 size) {
  552. if (addr == 0 || size == 0) {
  553. return;
  554. }
  555. {
  556. std::scoped_lock lock{texture_cache.mutex};
  557. texture_cache.WriteMemory(addr, size);
  558. }
  559. {
  560. std::scoped_lock lock{buffer_cache.mutex};
  561. buffer_cache.CachedWriteMemory(addr, size);
  562. }
  563. pipeline_cache.InvalidateRegion(addr, size);
  564. }
  565. void RasterizerVulkan::InvalidateGPUCache() {
  566. gpu.InvalidateGPUCache();
  567. }
  568. void RasterizerVulkan::UnmapMemory(VAddr addr, u64 size) {
  569. {
  570. std::scoped_lock lock{texture_cache.mutex};
  571. texture_cache.UnmapMemory(addr, size);
  572. }
  573. {
  574. std::scoped_lock lock{buffer_cache.mutex};
  575. buffer_cache.WriteMemory(addr, size);
  576. }
  577. pipeline_cache.OnCacheInvalidation(addr, size);
  578. }
  579. void RasterizerVulkan::ModifyGPUMemory(size_t as_id, GPUVAddr addr, u64 size) {
  580. {
  581. std::scoped_lock lock{texture_cache.mutex};
  582. texture_cache.UnmapGPUMemory(as_id, addr, size);
  583. }
  584. }
  585. void RasterizerVulkan::SignalFence(std::function<void()>&& func) {
  586. fence_manager.SignalFence(std::move(func));
  587. }
  588. void RasterizerVulkan::SyncOperation(std::function<void()>&& func) {
  589. fence_manager.SyncOperation(std::move(func));
  590. }
  591. void RasterizerVulkan::SignalSyncPoint(u32 value) {
  592. fence_manager.SignalSyncPoint(value);
  593. }
  594. void RasterizerVulkan::SignalReference() {
  595. fence_manager.SignalReference();
  596. }
  597. void RasterizerVulkan::ReleaseFences(bool force) {
  598. fence_manager.WaitPendingFences(force);
  599. }
  600. void RasterizerVulkan::FlushAndInvalidateRegion(VAddr addr, u64 size,
  601. VideoCommon::CacheType which) {
  602. if (Settings::IsGPULevelExtreme()) {
  603. FlushRegion(addr, size, which);
  604. }
  605. InvalidateRegion(addr, size, which);
  606. }
  607. void RasterizerVulkan::WaitForIdle() {
  608. // Everything but wait pixel operations. This intentionally includes FRAGMENT_SHADER_BIT because
  609. // fragment shaders can still write storage buffers.
  610. VkPipelineStageFlags flags =
  611. VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_VERTEX_INPUT_BIT |
  612. VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
  613. VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
  614. VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
  615. VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
  616. if (device.IsExtTransformFeedbackSupported()) {
  617. flags |= VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT;
  618. }
  619. query_cache.NotifyWFI();
  620. scheduler.RequestOutsideRenderPassOperationContext();
  621. scheduler.Record([event = *wfi_event, flags](vk::CommandBuffer cmdbuf) {
  622. cmdbuf.SetEvent(event, flags);
  623. cmdbuf.WaitEvents(event, flags, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, {}, {}, {});
  624. });
  625. fence_manager.SignalOrdering();
  626. }
  627. void RasterizerVulkan::FragmentBarrier() {
  628. // We already put barriers when a render pass finishes
  629. scheduler.RequestOutsideRenderPassOperationContext();
  630. }
  631. void RasterizerVulkan::TiledCacheBarrier() {
  632. // TODO: Implementing tiled barriers requires rewriting a good chunk of the Vulkan backend
  633. }
  634. void RasterizerVulkan::FlushCommands() {
  635. if (draw_counter == 0) {
  636. return;
  637. }
  638. draw_counter = 0;
  639. scheduler.Flush();
  640. }
  641. void RasterizerVulkan::TickFrame() {
  642. draw_counter = 0;
  643. guest_descriptor_queue.TickFrame();
  644. compute_pass_descriptor_queue.TickFrame();
  645. fence_manager.TickFrame();
  646. staging_pool.TickFrame();
  647. {
  648. std::scoped_lock lock{texture_cache.mutex};
  649. texture_cache.TickFrame();
  650. }
  651. {
  652. std::scoped_lock lock{buffer_cache.mutex};
  653. buffer_cache.TickFrame();
  654. }
  655. }
  656. bool RasterizerVulkan::AccelerateConditionalRendering() {
  657. gpu_memory->FlushCaching();
  658. return query_cache.AccelerateHostConditionalRendering();
  659. }
  660. bool RasterizerVulkan::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Surface& src,
  661. const Tegra::Engines::Fermi2D::Surface& dst,
  662. const Tegra::Engines::Fermi2D::Config& copy_config) {
  663. std::scoped_lock lock{texture_cache.mutex};
  664. return texture_cache.BlitImage(dst, src, copy_config);
  665. }
  666. Tegra::Engines::AccelerateDMAInterface& RasterizerVulkan::AccessAccelerateDMA() {
  667. return accelerate_dma;
  668. }
  669. void RasterizerVulkan::AccelerateInlineToMemory(GPUVAddr address, size_t copy_size,
  670. std::span<const u8> memory) {
  671. auto cpu_addr = gpu_memory->GpuToCpuAddress(address);
  672. if (!cpu_addr) [[unlikely]] {
  673. gpu_memory->WriteBlock(address, memory.data(), copy_size);
  674. return;
  675. }
  676. gpu_memory->WriteBlockUnsafe(address, memory.data(), copy_size);
  677. {
  678. std::unique_lock<std::recursive_mutex> lock{buffer_cache.mutex};
  679. if (!buffer_cache.InlineMemory(*cpu_addr, copy_size, memory)) {
  680. buffer_cache.WriteMemory(*cpu_addr, copy_size);
  681. }
  682. }
  683. {
  684. std::scoped_lock lock_texture{texture_cache.mutex};
  685. texture_cache.WriteMemory(*cpu_addr, copy_size);
  686. }
  687. pipeline_cache.InvalidateRegion(*cpu_addr, copy_size);
  688. query_cache.InvalidateRegion(*cpu_addr, copy_size);
  689. }
  690. bool RasterizerVulkan::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  691. VAddr framebuffer_addr, u32 pixel_stride) {
  692. if (!framebuffer_addr) {
  693. return false;
  694. }
  695. std::scoped_lock lock{texture_cache.mutex};
  696. ImageView* const image_view = texture_cache.TryFindFramebufferImageView(framebuffer_addr);
  697. if (!image_view) {
  698. return false;
  699. }
  700. query_cache.NotifySegment(false);
  701. screen_info.image = image_view->ImageHandle();
  702. screen_info.image_view = image_view->Handle(Shader::TextureType::Color2D);
  703. screen_info.width = image_view->size.width;
  704. screen_info.height = image_view->size.height;
  705. screen_info.is_srgb = VideoCore::Surface::IsPixelFormatSRGB(image_view->format);
  706. return true;
  707. }
  708. void RasterizerVulkan::LoadDiskResources(u64 title_id, std::stop_token stop_loading,
  709. const VideoCore::DiskResourceLoadCallback& callback) {
  710. pipeline_cache.LoadDiskResources(title_id, stop_loading, callback);
  711. }
  712. void RasterizerVulkan::FlushWork() {
  713. #ifdef ANDROID
  714. static constexpr u32 DRAWS_TO_DISPATCH = 1024;
  715. #else
  716. static constexpr u32 DRAWS_TO_DISPATCH = 4096;
  717. #endif // ANDROID
  718. // Only check multiples of 8 draws
  719. static_assert(DRAWS_TO_DISPATCH % 8 == 0);
  720. if ((++draw_counter & 7) != 7) {
  721. return;
  722. }
  723. if (draw_counter < DRAWS_TO_DISPATCH) {
  724. // Send recorded tasks to the worker thread
  725. scheduler.DispatchWork();
  726. return;
  727. }
  728. // Otherwise (every certain number of draws) flush execution.
  729. // This submits commands to the Vulkan driver.
  730. scheduler.Flush();
  731. draw_counter = 0;
  732. }
  733. AccelerateDMA::AccelerateDMA(BufferCache& buffer_cache_, TextureCache& texture_cache_,
  734. Scheduler& scheduler_)
  735. : buffer_cache{buffer_cache_}, texture_cache{texture_cache_}, scheduler{scheduler_} {}
  736. bool AccelerateDMA::BufferClear(GPUVAddr src_address, u64 amount, u32 value) {
  737. std::scoped_lock lock{buffer_cache.mutex};
  738. return buffer_cache.DMAClear(src_address, amount, value);
  739. }
  740. bool AccelerateDMA::BufferCopy(GPUVAddr src_address, GPUVAddr dest_address, u64 amount) {
  741. std::scoped_lock lock{buffer_cache.mutex};
  742. return buffer_cache.DMACopy(src_address, dest_address, amount);
  743. }
  744. template <bool IS_IMAGE_UPLOAD>
  745. bool AccelerateDMA::DmaBufferImageCopy(const Tegra::DMA::ImageCopy& copy_info,
  746. const Tegra::DMA::BufferOperand& buffer_operand,
  747. const Tegra::DMA::ImageOperand& image_operand) {
  748. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  749. const auto image_id = texture_cache.DmaImageId(image_operand, IS_IMAGE_UPLOAD);
  750. if (image_id == VideoCommon::NULL_IMAGE_ID) {
  751. return false;
  752. }
  753. const u32 buffer_size = static_cast<u32>(buffer_operand.pitch * buffer_operand.height);
  754. static constexpr auto sync_info = VideoCommon::ObtainBufferSynchronize::FullSynchronize;
  755. const auto post_op = IS_IMAGE_UPLOAD ? VideoCommon::ObtainBufferOperation::DoNothing
  756. : VideoCommon::ObtainBufferOperation::MarkAsWritten;
  757. const auto [buffer, offset] =
  758. buffer_cache.ObtainBuffer(buffer_operand.address, buffer_size, sync_info, post_op);
  759. const auto [image, copy] = texture_cache.DmaBufferImageCopy(
  760. copy_info, buffer_operand, image_operand, image_id, IS_IMAGE_UPLOAD);
  761. const std::span copy_span{&copy, 1};
  762. if constexpr (IS_IMAGE_UPLOAD) {
  763. texture_cache.PrepareImage(image_id, true, false);
  764. image->UploadMemory(buffer->Handle(), offset, copy_span);
  765. } else {
  766. if (offset % BytesPerBlock(image->info.format)) {
  767. return false;
  768. }
  769. texture_cache.DownloadImageIntoBuffer(image, buffer->Handle(), offset, copy_span,
  770. buffer_operand.address, buffer_size);
  771. }
  772. return true;
  773. }
  774. bool AccelerateDMA::ImageToBuffer(const Tegra::DMA::ImageCopy& copy_info,
  775. const Tegra::DMA::ImageOperand& image_operand,
  776. const Tegra::DMA::BufferOperand& buffer_operand) {
  777. return DmaBufferImageCopy<false>(copy_info, buffer_operand, image_operand);
  778. }
  779. bool AccelerateDMA::BufferToImage(const Tegra::DMA::ImageCopy& copy_info,
  780. const Tegra::DMA::BufferOperand& buffer_operand,
  781. const Tegra::DMA::ImageOperand& image_operand) {
  782. return DmaBufferImageCopy<true>(copy_info, buffer_operand, image_operand);
  783. }
  784. void RasterizerVulkan::UpdateDynamicStates() {
  785. auto& regs = maxwell3d->regs;
  786. UpdateViewportsState(regs);
  787. UpdateScissorsState(regs);
  788. UpdateDepthBias(regs);
  789. UpdateBlendConstants(regs);
  790. UpdateDepthBounds(regs);
  791. UpdateStencilFaces(regs);
  792. UpdateLineWidth(regs);
  793. if (device.IsExtExtendedDynamicStateSupported()) {
  794. UpdateCullMode(regs);
  795. UpdateDepthCompareOp(regs);
  796. UpdateFrontFace(regs);
  797. UpdateStencilOp(regs);
  798. if (device.IsExtVertexInputDynamicStateSupported()) {
  799. UpdateVertexInput(regs);
  800. }
  801. if (state_tracker.TouchStateEnable()) {
  802. UpdateDepthBoundsTestEnable(regs);
  803. UpdateDepthTestEnable(regs);
  804. UpdateDepthWriteEnable(regs);
  805. UpdateStencilTestEnable(regs);
  806. if (device.IsExtExtendedDynamicState2Supported()) {
  807. UpdatePrimitiveRestartEnable(regs);
  808. UpdateRasterizerDiscardEnable(regs);
  809. UpdateDepthBiasEnable(regs);
  810. }
  811. if (device.IsExtExtendedDynamicState3EnablesSupported()) {
  812. UpdateLogicOpEnable(regs);
  813. UpdateDepthClampEnable(regs);
  814. }
  815. }
  816. if (device.IsExtExtendedDynamicState2ExtrasSupported()) {
  817. UpdateLogicOp(regs);
  818. }
  819. if (device.IsExtExtendedDynamicState3Supported()) {
  820. UpdateBlending(regs);
  821. }
  822. }
  823. }
  824. void RasterizerVulkan::HandleTransformFeedback() {
  825. const auto& regs = maxwell3d->regs;
  826. if (!device.IsExtTransformFeedbackSupported()) {
  827. LOG_ERROR(Render_Vulkan, "Transform feedbacks used but not supported");
  828. return;
  829. }
  830. query_cache.CounterEnable(VideoCommon::QueryType::StreamingByteCount,
  831. regs.transform_feedback_enabled);
  832. if (regs.transform_feedback_enabled != 0) {
  833. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderType::TessellationInit) ||
  834. regs.IsShaderConfigEnabled(Maxwell::ShaderType::Tessellation));
  835. }
  836. }
  837. void RasterizerVulkan::UpdateViewportsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  838. if (!state_tracker.TouchViewports()) {
  839. return;
  840. }
  841. if (!regs.viewport_scale_offset_enabled) {
  842. const auto x = static_cast<float>(regs.surface_clip.x);
  843. const auto y = static_cast<float>(regs.surface_clip.y);
  844. const auto width = static_cast<float>(regs.surface_clip.width);
  845. const auto height = static_cast<float>(regs.surface_clip.height);
  846. VkViewport viewport{
  847. .x = x,
  848. .y = y,
  849. .width = width != 0.0f ? width : 1.0f,
  850. .height = height != 0.0f ? height : 1.0f,
  851. .minDepth = 0.0f,
  852. .maxDepth = 1.0f,
  853. };
  854. scheduler.Record([viewport](vk::CommandBuffer cmdbuf) { cmdbuf.SetViewport(0, viewport); });
  855. return;
  856. }
  857. const bool is_rescaling{texture_cache.IsRescaling()};
  858. const float scale = is_rescaling ? Settings::values.resolution_info.up_factor : 1.0f;
  859. const std::array viewport_list{
  860. GetViewportState(device, regs, 0, scale), GetViewportState(device, regs, 1, scale),
  861. GetViewportState(device, regs, 2, scale), GetViewportState(device, regs, 3, scale),
  862. GetViewportState(device, regs, 4, scale), GetViewportState(device, regs, 5, scale),
  863. GetViewportState(device, regs, 6, scale), GetViewportState(device, regs, 7, scale),
  864. GetViewportState(device, regs, 8, scale), GetViewportState(device, regs, 9, scale),
  865. GetViewportState(device, regs, 10, scale), GetViewportState(device, regs, 11, scale),
  866. GetViewportState(device, regs, 12, scale), GetViewportState(device, regs, 13, scale),
  867. GetViewportState(device, regs, 14, scale), GetViewportState(device, regs, 15, scale),
  868. };
  869. scheduler.Record([this, viewport_list](vk::CommandBuffer cmdbuf) {
  870. const u32 num_viewports = std::min<u32>(device.GetMaxViewports(), Maxwell::NumViewports);
  871. const vk::Span<VkViewport> viewports(viewport_list.data(), num_viewports);
  872. cmdbuf.SetViewport(0, viewports);
  873. });
  874. }
  875. void RasterizerVulkan::UpdateScissorsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  876. if (!state_tracker.TouchScissors()) {
  877. return;
  878. }
  879. u32 up_scale = 1;
  880. u32 down_shift = 0;
  881. if (texture_cache.IsRescaling()) {
  882. up_scale = Settings::values.resolution_info.up_scale;
  883. down_shift = Settings::values.resolution_info.down_shift;
  884. }
  885. const std::array scissor_list{
  886. GetScissorState(regs, 0, up_scale, down_shift),
  887. GetScissorState(regs, 1, up_scale, down_shift),
  888. GetScissorState(regs, 2, up_scale, down_shift),
  889. GetScissorState(regs, 3, up_scale, down_shift),
  890. GetScissorState(regs, 4, up_scale, down_shift),
  891. GetScissorState(regs, 5, up_scale, down_shift),
  892. GetScissorState(regs, 6, up_scale, down_shift),
  893. GetScissorState(regs, 7, up_scale, down_shift),
  894. GetScissorState(regs, 8, up_scale, down_shift),
  895. GetScissorState(regs, 9, up_scale, down_shift),
  896. GetScissorState(regs, 10, up_scale, down_shift),
  897. GetScissorState(regs, 11, up_scale, down_shift),
  898. GetScissorState(regs, 12, up_scale, down_shift),
  899. GetScissorState(regs, 13, up_scale, down_shift),
  900. GetScissorState(regs, 14, up_scale, down_shift),
  901. GetScissorState(regs, 15, up_scale, down_shift),
  902. };
  903. scheduler.Record([this, scissor_list](vk::CommandBuffer cmdbuf) {
  904. const u32 num_scissors = std::min<u32>(device.GetMaxViewports(), Maxwell::NumViewports);
  905. const vk::Span<VkRect2D> scissors(scissor_list.data(), num_scissors);
  906. cmdbuf.SetScissor(0, scissors);
  907. });
  908. }
  909. void RasterizerVulkan::UpdateDepthBias(Tegra::Engines::Maxwell3D::Regs& regs) {
  910. if (!state_tracker.TouchDepthBias()) {
  911. return;
  912. }
  913. float units = regs.depth_bias / 2.0f;
  914. const bool is_d24 = regs.zeta.format == Tegra::DepthFormat::Z24_UNORM_S8_UINT ||
  915. regs.zeta.format == Tegra::DepthFormat::X8Z24_UNORM ||
  916. regs.zeta.format == Tegra::DepthFormat::S8Z24_UNORM ||
  917. regs.zeta.format == Tegra::DepthFormat::V8Z24_UNORM;
  918. bool force_unorm = ([&] {
  919. if (!is_d24 || device.SupportsD24DepthBuffer()) {
  920. return false;
  921. }
  922. if (device.IsExtDepthBiasControlSupported()) {
  923. return true;
  924. }
  925. if (!Settings::values.renderer_amdvlk_depth_bias_workaround) {
  926. return false;
  927. }
  928. // the base formulas can be obtained from here:
  929. // https://docs.microsoft.com/en-us/windows/win32/direct3d11/d3d10-graphics-programming-guide-output-merger-stage-depth-bias
  930. const double rescale_factor =
  931. static_cast<double>(1ULL << (32 - 24)) / (static_cast<double>(0x1.ep+127));
  932. units = static_cast<float>(static_cast<double>(units) * rescale_factor);
  933. return false;
  934. })();
  935. scheduler.Record([constant = units, clamp = regs.depth_bias_clamp,
  936. factor = regs.slope_scale_depth_bias, force_unorm,
  937. precise = device.HasExactDepthBiasControl()](vk::CommandBuffer cmdbuf) {
  938. if (force_unorm) {
  939. VkDepthBiasRepresentationInfoEXT info{
  940. .sType = VK_STRUCTURE_TYPE_DEPTH_BIAS_REPRESENTATION_INFO_EXT,
  941. .pNext = nullptr,
  942. .depthBiasRepresentation =
  943. VK_DEPTH_BIAS_REPRESENTATION_LEAST_REPRESENTABLE_VALUE_FORCE_UNORM_EXT,
  944. .depthBiasExact = precise ? VK_TRUE : VK_FALSE,
  945. };
  946. cmdbuf.SetDepthBias(constant, clamp, factor, &info);
  947. return;
  948. }
  949. cmdbuf.SetDepthBias(constant, clamp, factor);
  950. });
  951. }
  952. void RasterizerVulkan::UpdateBlendConstants(Tegra::Engines::Maxwell3D::Regs& regs) {
  953. if (!state_tracker.TouchBlendConstants()) {
  954. return;
  955. }
  956. const std::array blend_color = {regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  957. regs.blend_color.a};
  958. scheduler.Record(
  959. [blend_color](vk::CommandBuffer cmdbuf) { cmdbuf.SetBlendConstants(blend_color.data()); });
  960. }
  961. void RasterizerVulkan::UpdateDepthBounds(Tegra::Engines::Maxwell3D::Regs& regs) {
  962. if (!state_tracker.TouchDepthBounds()) {
  963. return;
  964. }
  965. scheduler.Record([min = regs.depth_bounds[0], max = regs.depth_bounds[1]](
  966. vk::CommandBuffer cmdbuf) { cmdbuf.SetDepthBounds(min, max); });
  967. }
  968. void RasterizerVulkan::UpdateStencilFaces(Tegra::Engines::Maxwell3D::Regs& regs) {
  969. if (!state_tracker.TouchStencilProperties()) {
  970. return;
  971. }
  972. bool update_references = state_tracker.TouchStencilReference();
  973. bool update_write_mask = state_tracker.TouchStencilWriteMask();
  974. bool update_compare_masks = state_tracker.TouchStencilCompare();
  975. if (state_tracker.TouchStencilSide(regs.stencil_two_side_enable != 0)) {
  976. update_references = true;
  977. update_write_mask = true;
  978. update_compare_masks = true;
  979. }
  980. if (update_references) {
  981. [&]() {
  982. if (regs.stencil_two_side_enable) {
  983. if (!state_tracker.CheckStencilReferenceFront(regs.stencil_front_ref) &&
  984. !state_tracker.CheckStencilReferenceBack(regs.stencil_back_ref)) {
  985. return;
  986. }
  987. } else {
  988. if (!state_tracker.CheckStencilReferenceFront(regs.stencil_front_ref)) {
  989. return;
  990. }
  991. }
  992. scheduler.Record([front_ref = regs.stencil_front_ref, back_ref = regs.stencil_back_ref,
  993. two_sided = regs.stencil_two_side_enable](vk::CommandBuffer cmdbuf) {
  994. const bool set_back = two_sided && front_ref != back_ref;
  995. // Front face
  996. cmdbuf.SetStencilReference(set_back ? VK_STENCIL_FACE_FRONT_BIT
  997. : VK_STENCIL_FACE_FRONT_AND_BACK,
  998. front_ref);
  999. if (set_back) {
  1000. cmdbuf.SetStencilReference(VK_STENCIL_FACE_BACK_BIT, back_ref);
  1001. }
  1002. });
  1003. }();
  1004. }
  1005. if (update_write_mask) {
  1006. [&]() {
  1007. if (regs.stencil_two_side_enable) {
  1008. if (!state_tracker.CheckStencilWriteMaskFront(regs.stencil_front_mask) &&
  1009. !state_tracker.CheckStencilWriteMaskBack(regs.stencil_back_mask)) {
  1010. return;
  1011. }
  1012. } else {
  1013. if (!state_tracker.CheckStencilWriteMaskFront(regs.stencil_front_mask)) {
  1014. return;
  1015. }
  1016. }
  1017. scheduler.Record([front_write_mask = regs.stencil_front_mask,
  1018. back_write_mask = regs.stencil_back_mask,
  1019. two_sided = regs.stencil_two_side_enable](vk::CommandBuffer cmdbuf) {
  1020. const bool set_back = two_sided && front_write_mask != back_write_mask;
  1021. // Front face
  1022. cmdbuf.SetStencilWriteMask(set_back ? VK_STENCIL_FACE_FRONT_BIT
  1023. : VK_STENCIL_FACE_FRONT_AND_BACK,
  1024. front_write_mask);
  1025. if (set_back) {
  1026. cmdbuf.SetStencilWriteMask(VK_STENCIL_FACE_BACK_BIT, back_write_mask);
  1027. }
  1028. });
  1029. }();
  1030. }
  1031. if (update_compare_masks) {
  1032. [&]() {
  1033. if (regs.stencil_two_side_enable) {
  1034. if (!state_tracker.CheckStencilCompareMaskFront(regs.stencil_front_func_mask) &&
  1035. !state_tracker.CheckStencilCompareMaskBack(regs.stencil_back_func_mask)) {
  1036. return;
  1037. }
  1038. } else {
  1039. if (!state_tracker.CheckStencilCompareMaskFront(regs.stencil_front_func_mask)) {
  1040. return;
  1041. }
  1042. }
  1043. scheduler.Record([front_test_mask = regs.stencil_front_func_mask,
  1044. back_test_mask = regs.stencil_back_func_mask,
  1045. two_sided = regs.stencil_two_side_enable](vk::CommandBuffer cmdbuf) {
  1046. const bool set_back = two_sided && front_test_mask != back_test_mask;
  1047. // Front face
  1048. cmdbuf.SetStencilCompareMask(set_back ? VK_STENCIL_FACE_FRONT_BIT
  1049. : VK_STENCIL_FACE_FRONT_AND_BACK,
  1050. front_test_mask);
  1051. if (set_back) {
  1052. cmdbuf.SetStencilCompareMask(VK_STENCIL_FACE_BACK_BIT, back_test_mask);
  1053. }
  1054. });
  1055. }();
  1056. }
  1057. state_tracker.ClearStencilReset();
  1058. }
  1059. void RasterizerVulkan::UpdateLineWidth(Tegra::Engines::Maxwell3D::Regs& regs) {
  1060. if (!state_tracker.TouchLineWidth()) {
  1061. return;
  1062. }
  1063. const float width =
  1064. regs.line_anti_alias_enable ? regs.line_width_smooth : regs.line_width_aliased;
  1065. scheduler.Record([width](vk::CommandBuffer cmdbuf) { cmdbuf.SetLineWidth(width); });
  1066. }
  1067. void RasterizerVulkan::UpdateCullMode(Tegra::Engines::Maxwell3D::Regs& regs) {
  1068. if (!state_tracker.TouchCullMode()) {
  1069. return;
  1070. }
  1071. scheduler.Record([enabled = regs.gl_cull_test_enabled,
  1072. cull_face = regs.gl_cull_face](vk::CommandBuffer cmdbuf) {
  1073. cmdbuf.SetCullModeEXT(enabled ? MaxwellToVK::CullFace(cull_face) : VK_CULL_MODE_NONE);
  1074. });
  1075. }
  1076. void RasterizerVulkan::UpdateDepthBoundsTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1077. if (!state_tracker.TouchDepthBoundsTestEnable()) {
  1078. return;
  1079. }
  1080. bool enabled = regs.depth_bounds_enable;
  1081. if (enabled && !device.IsDepthBoundsSupported()) {
  1082. LOG_WARNING(Render_Vulkan, "Depth bounds is enabled but not supported");
  1083. enabled = false;
  1084. }
  1085. scheduler.Record([enable = enabled](vk::CommandBuffer cmdbuf) {
  1086. cmdbuf.SetDepthBoundsTestEnableEXT(enable);
  1087. });
  1088. }
  1089. void RasterizerVulkan::UpdateDepthTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1090. if (!state_tracker.TouchDepthTestEnable()) {
  1091. return;
  1092. }
  1093. scheduler.Record([enable = regs.depth_test_enable](vk::CommandBuffer cmdbuf) {
  1094. cmdbuf.SetDepthTestEnableEXT(enable);
  1095. });
  1096. }
  1097. void RasterizerVulkan::UpdateDepthWriteEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1098. if (!state_tracker.TouchDepthWriteEnable()) {
  1099. return;
  1100. }
  1101. scheduler.Record([enable = regs.depth_write_enabled](vk::CommandBuffer cmdbuf) {
  1102. cmdbuf.SetDepthWriteEnableEXT(enable);
  1103. });
  1104. }
  1105. void RasterizerVulkan::UpdatePrimitiveRestartEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1106. if (!state_tracker.TouchPrimitiveRestartEnable()) {
  1107. return;
  1108. }
  1109. scheduler.Record([enable = regs.primitive_restart.enabled](vk::CommandBuffer cmdbuf) {
  1110. cmdbuf.SetPrimitiveRestartEnableEXT(enable);
  1111. });
  1112. }
  1113. void RasterizerVulkan::UpdateRasterizerDiscardEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1114. if (!state_tracker.TouchRasterizerDiscardEnable()) {
  1115. return;
  1116. }
  1117. scheduler.Record([disable = regs.rasterize_enable](vk::CommandBuffer cmdbuf) {
  1118. cmdbuf.SetRasterizerDiscardEnableEXT(disable == 0);
  1119. });
  1120. }
  1121. void RasterizerVulkan::UpdateDepthBiasEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1122. if (!state_tracker.TouchDepthBiasEnable()) {
  1123. return;
  1124. }
  1125. constexpr size_t POINT = 0;
  1126. constexpr size_t LINE = 1;
  1127. constexpr size_t POLYGON = 2;
  1128. static constexpr std::array POLYGON_OFFSET_ENABLE_LUT = {
  1129. POINT, // Points
  1130. LINE, // Lines
  1131. LINE, // LineLoop
  1132. LINE, // LineStrip
  1133. POLYGON, // Triangles
  1134. POLYGON, // TriangleStrip
  1135. POLYGON, // TriangleFan
  1136. POLYGON, // Quads
  1137. POLYGON, // QuadStrip
  1138. POLYGON, // Polygon
  1139. LINE, // LinesAdjacency
  1140. LINE, // LineStripAdjacency
  1141. POLYGON, // TrianglesAdjacency
  1142. POLYGON, // TriangleStripAdjacency
  1143. POLYGON, // Patches
  1144. };
  1145. const std::array enabled_lut{
  1146. regs.polygon_offset_point_enable,
  1147. regs.polygon_offset_line_enable,
  1148. regs.polygon_offset_fill_enable,
  1149. };
  1150. const u32 topology_index = static_cast<u32>(maxwell3d->draw_manager->GetDrawState().topology);
  1151. const u32 enable = enabled_lut[POLYGON_OFFSET_ENABLE_LUT[topology_index]];
  1152. scheduler.Record(
  1153. [enable](vk::CommandBuffer cmdbuf) { cmdbuf.SetDepthBiasEnableEXT(enable != 0); });
  1154. }
  1155. void RasterizerVulkan::UpdateLogicOpEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1156. if (!state_tracker.TouchLogicOpEnable()) {
  1157. return;
  1158. }
  1159. scheduler.Record([enable = regs.logic_op.enable](vk::CommandBuffer cmdbuf) {
  1160. cmdbuf.SetLogicOpEnableEXT(enable != 0);
  1161. });
  1162. }
  1163. void RasterizerVulkan::UpdateDepthClampEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1164. if (!state_tracker.TouchDepthClampEnable()) {
  1165. return;
  1166. }
  1167. bool is_enabled = !(regs.viewport_clip_control.geometry_clip ==
  1168. Maxwell::ViewportClipControl::GeometryClip::Passthrough ||
  1169. regs.viewport_clip_control.geometry_clip ==
  1170. Maxwell::ViewportClipControl::GeometryClip::FrustumXYZ ||
  1171. regs.viewport_clip_control.geometry_clip ==
  1172. Maxwell::ViewportClipControl::GeometryClip::FrustumZ);
  1173. scheduler.Record(
  1174. [is_enabled](vk::CommandBuffer cmdbuf) { cmdbuf.SetDepthClampEnableEXT(is_enabled); });
  1175. }
  1176. void RasterizerVulkan::UpdateDepthCompareOp(Tegra::Engines::Maxwell3D::Regs& regs) {
  1177. if (!state_tracker.TouchDepthCompareOp()) {
  1178. return;
  1179. }
  1180. scheduler.Record([func = regs.depth_test_func](vk::CommandBuffer cmdbuf) {
  1181. cmdbuf.SetDepthCompareOpEXT(MaxwellToVK::ComparisonOp(func));
  1182. });
  1183. }
  1184. void RasterizerVulkan::UpdateFrontFace(Tegra::Engines::Maxwell3D::Regs& regs) {
  1185. if (!state_tracker.TouchFrontFace()) {
  1186. return;
  1187. }
  1188. VkFrontFace front_face = MaxwellToVK::FrontFace(regs.gl_front_face);
  1189. if (regs.window_origin.flip_y != 0) {
  1190. front_face = front_face == VK_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_COUNTER_CLOCKWISE
  1191. : VK_FRONT_FACE_CLOCKWISE;
  1192. }
  1193. scheduler.Record(
  1194. [front_face](vk::CommandBuffer cmdbuf) { cmdbuf.SetFrontFaceEXT(front_face); });
  1195. }
  1196. void RasterizerVulkan::UpdateStencilOp(Tegra::Engines::Maxwell3D::Regs& regs) {
  1197. if (!state_tracker.TouchStencilOp()) {
  1198. return;
  1199. }
  1200. const Maxwell::StencilOp::Op fail = regs.stencil_front_op.fail;
  1201. const Maxwell::StencilOp::Op zfail = regs.stencil_front_op.zfail;
  1202. const Maxwell::StencilOp::Op zpass = regs.stencil_front_op.zpass;
  1203. const Maxwell::ComparisonOp compare = regs.stencil_front_op.func;
  1204. if (regs.stencil_two_side_enable) {
  1205. // Separate stencil op per face
  1206. const Maxwell::StencilOp::Op back_fail = regs.stencil_back_op.fail;
  1207. const Maxwell::StencilOp::Op back_zfail = regs.stencil_back_op.zfail;
  1208. const Maxwell::StencilOp::Op back_zpass = regs.stencil_back_op.zpass;
  1209. const Maxwell::ComparisonOp back_compare = regs.stencil_back_op.func;
  1210. scheduler.Record([fail, zfail, zpass, compare, back_fail, back_zfail, back_zpass,
  1211. back_compare](vk::CommandBuffer cmdbuf) {
  1212. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_FRONT_BIT, MaxwellToVK::StencilOp(fail),
  1213. MaxwellToVK::StencilOp(zpass), MaxwellToVK::StencilOp(zfail),
  1214. MaxwellToVK::ComparisonOp(compare));
  1215. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_BACK_BIT, MaxwellToVK::StencilOp(back_fail),
  1216. MaxwellToVK::StencilOp(back_zpass),
  1217. MaxwellToVK::StencilOp(back_zfail),
  1218. MaxwellToVK::ComparisonOp(back_compare));
  1219. });
  1220. } else {
  1221. // Front face defines the stencil op of both faces
  1222. scheduler.Record([fail, zfail, zpass, compare](vk::CommandBuffer cmdbuf) {
  1223. cmdbuf.SetStencilOpEXT(VK_STENCIL_FACE_FRONT_AND_BACK, MaxwellToVK::StencilOp(fail),
  1224. MaxwellToVK::StencilOp(zpass), MaxwellToVK::StencilOp(zfail),
  1225. MaxwellToVK::ComparisonOp(compare));
  1226. });
  1227. }
  1228. }
  1229. void RasterizerVulkan::UpdateLogicOp(Tegra::Engines::Maxwell3D::Regs& regs) {
  1230. if (!state_tracker.TouchLogicOp()) {
  1231. return;
  1232. }
  1233. const auto op_value = static_cast<u32>(regs.logic_op.op);
  1234. auto op = op_value >= 0x1500 && op_value < 0x1510 ? static_cast<VkLogicOp>(op_value - 0x1500)
  1235. : VK_LOGIC_OP_NO_OP;
  1236. scheduler.Record([op](vk::CommandBuffer cmdbuf) { cmdbuf.SetLogicOpEXT(op); });
  1237. }
  1238. void RasterizerVulkan::UpdateBlending(Tegra::Engines::Maxwell3D::Regs& regs) {
  1239. if (!state_tracker.TouchBlending()) {
  1240. return;
  1241. }
  1242. if (state_tracker.TouchColorMask()) {
  1243. std::array<VkColorComponentFlags, Maxwell::NumRenderTargets> setup_masks{};
  1244. for (size_t index = 0; index < Maxwell::NumRenderTargets; index++) {
  1245. const auto& mask = regs.color_mask[regs.color_mask_common ? 0 : index];
  1246. auto& current = setup_masks[index];
  1247. if (mask.R) {
  1248. current |= VK_COLOR_COMPONENT_R_BIT;
  1249. }
  1250. if (mask.G) {
  1251. current |= VK_COLOR_COMPONENT_G_BIT;
  1252. }
  1253. if (mask.B) {
  1254. current |= VK_COLOR_COMPONENT_B_BIT;
  1255. }
  1256. if (mask.A) {
  1257. current |= VK_COLOR_COMPONENT_A_BIT;
  1258. }
  1259. }
  1260. scheduler.Record([setup_masks](vk::CommandBuffer cmdbuf) {
  1261. cmdbuf.SetColorWriteMaskEXT(0, setup_masks);
  1262. });
  1263. }
  1264. if (state_tracker.TouchBlendEnable()) {
  1265. std::array<VkBool32, Maxwell::NumRenderTargets> setup_enables{};
  1266. std::ranges::transform(
  1267. regs.blend.enable, setup_enables.begin(),
  1268. [&](const auto& is_enabled) { return is_enabled != 0 ? VK_TRUE : VK_FALSE; });
  1269. scheduler.Record([setup_enables](vk::CommandBuffer cmdbuf) {
  1270. cmdbuf.SetColorBlendEnableEXT(0, setup_enables);
  1271. });
  1272. }
  1273. if (state_tracker.TouchBlendEquations()) {
  1274. std::array<VkColorBlendEquationEXT, Maxwell::NumRenderTargets> setup_blends{};
  1275. for (size_t index = 0; index < Maxwell::NumRenderTargets; index++) {
  1276. const auto blend_setup = [&]<typename T>(const T& guest_blend) {
  1277. auto& host_blend = setup_blends[index];
  1278. host_blend.srcColorBlendFactor = MaxwellToVK::BlendFactor(guest_blend.color_source);
  1279. host_blend.dstColorBlendFactor = MaxwellToVK::BlendFactor(guest_blend.color_dest);
  1280. host_blend.colorBlendOp = MaxwellToVK::BlendEquation(guest_blend.color_op);
  1281. host_blend.srcAlphaBlendFactor = MaxwellToVK::BlendFactor(guest_blend.alpha_source);
  1282. host_blend.dstAlphaBlendFactor = MaxwellToVK::BlendFactor(guest_blend.alpha_dest);
  1283. host_blend.alphaBlendOp = MaxwellToVK::BlendEquation(guest_blend.alpha_op);
  1284. };
  1285. if (!regs.blend_per_target_enabled) {
  1286. blend_setup(regs.blend);
  1287. continue;
  1288. }
  1289. blend_setup(regs.blend_per_target[index]);
  1290. }
  1291. scheduler.Record([setup_blends](vk::CommandBuffer cmdbuf) {
  1292. cmdbuf.SetColorBlendEquationEXT(0, setup_blends);
  1293. });
  1294. }
  1295. }
  1296. void RasterizerVulkan::UpdateStencilTestEnable(Tegra::Engines::Maxwell3D::Regs& regs) {
  1297. if (!state_tracker.TouchStencilTestEnable()) {
  1298. return;
  1299. }
  1300. scheduler.Record([enable = regs.stencil_enable](vk::CommandBuffer cmdbuf) {
  1301. cmdbuf.SetStencilTestEnableEXT(enable);
  1302. });
  1303. }
  1304. void RasterizerVulkan::UpdateVertexInput(Tegra::Engines::Maxwell3D::Regs& regs) {
  1305. auto& dirty{maxwell3d->dirty.flags};
  1306. if (!dirty[Dirty::VertexInput]) {
  1307. return;
  1308. }
  1309. dirty[Dirty::VertexInput] = false;
  1310. boost::container::static_vector<VkVertexInputBindingDescription2EXT, 32> bindings;
  1311. boost::container::static_vector<VkVertexInputAttributeDescription2EXT, 32> attributes;
  1312. // There seems to be a bug on Nvidia's driver where updating only higher attributes ends up
  1313. // generating dirty state. Track the highest dirty attribute and update all attributes until
  1314. // that one.
  1315. size_t highest_dirty_attr{};
  1316. for (size_t index = 0; index < Maxwell::NumVertexAttributes; ++index) {
  1317. if (dirty[Dirty::VertexAttribute0 + index]) {
  1318. highest_dirty_attr = index;
  1319. }
  1320. }
  1321. for (size_t index = 0; index < highest_dirty_attr; ++index) {
  1322. const Maxwell::VertexAttribute attribute{regs.vertex_attrib_format[index]};
  1323. const u32 binding{attribute.buffer};
  1324. dirty[Dirty::VertexAttribute0 + index] = false;
  1325. dirty[Dirty::VertexBinding0 + static_cast<size_t>(binding)] = true;
  1326. if (!attribute.constant) {
  1327. attributes.push_back({
  1328. .sType = VK_STRUCTURE_TYPE_VERTEX_INPUT_ATTRIBUTE_DESCRIPTION_2_EXT,
  1329. .pNext = nullptr,
  1330. .location = static_cast<u32>(index),
  1331. .binding = binding,
  1332. .format = MaxwellToVK::VertexFormat(device, attribute.type, attribute.size),
  1333. .offset = attribute.offset,
  1334. });
  1335. }
  1336. }
  1337. for (size_t index = 0; index < Maxwell::NumVertexAttributes; ++index) {
  1338. if (!dirty[Dirty::VertexBinding0 + index]) {
  1339. continue;
  1340. }
  1341. dirty[Dirty::VertexBinding0 + index] = false;
  1342. const u32 binding{static_cast<u32>(index)};
  1343. const auto& input_binding{regs.vertex_streams[binding]};
  1344. const bool is_instanced{regs.vertex_stream_instances.IsInstancingEnabled(binding)};
  1345. bindings.push_back({
  1346. .sType = VK_STRUCTURE_TYPE_VERTEX_INPUT_BINDING_DESCRIPTION_2_EXT,
  1347. .pNext = nullptr,
  1348. .binding = binding,
  1349. .stride = input_binding.stride,
  1350. .inputRate = is_instanced ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX,
  1351. .divisor = is_instanced ? input_binding.frequency : 1,
  1352. });
  1353. }
  1354. scheduler.Record([bindings, attributes](vk::CommandBuffer cmdbuf) {
  1355. cmdbuf.SetVertexInputEXT(bindings, attributes);
  1356. });
  1357. }
  1358. void RasterizerVulkan::InitializeChannel(Tegra::Control::ChannelState& channel) {
  1359. CreateChannel(channel);
  1360. {
  1361. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  1362. texture_cache.CreateChannel(channel);
  1363. buffer_cache.CreateChannel(channel);
  1364. }
  1365. pipeline_cache.CreateChannel(channel);
  1366. query_cache.CreateChannel(channel);
  1367. state_tracker.SetupTables(channel);
  1368. }
  1369. void RasterizerVulkan::BindChannel(Tegra::Control::ChannelState& channel) {
  1370. const s32 channel_id = channel.bind_id;
  1371. BindToChannel(channel_id);
  1372. {
  1373. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  1374. texture_cache.BindToChannel(channel_id);
  1375. buffer_cache.BindToChannel(channel_id);
  1376. }
  1377. pipeline_cache.BindToChannel(channel_id);
  1378. query_cache.BindToChannel(channel_id);
  1379. state_tracker.ChangeChannel(channel);
  1380. state_tracker.InvalidateState();
  1381. }
  1382. void RasterizerVulkan::ReleaseChannel(s32 channel_id) {
  1383. EraseChannel(channel_id);
  1384. {
  1385. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  1386. texture_cache.EraseChannel(channel_id);
  1387. buffer_cache.EraseChannel(channel_id);
  1388. }
  1389. pipeline_cache.EraseChannel(channel_id);
  1390. query_cache.EraseChannel(channel_id);
  1391. }
  1392. } // namespace Vulkan