vk_rasterizer.cpp 60 KB

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