vk_rasterizer.cpp 63 KB

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