vk_rasterizer.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. // Copyright 2019 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <memory>
  7. #include <mutex>
  8. #include <vector>
  9. #include <boost/container/static_vector.hpp>
  10. #include <boost/functional/hash.hpp>
  11. #include "common/alignment.h"
  12. #include "common/assert.h"
  13. #include "common/logging/log.h"
  14. #include "common/microprofile.h"
  15. #include "core/core.h"
  16. #include "core/memory.h"
  17. #include "video_core/engines/kepler_compute.h"
  18. #include "video_core/engines/maxwell_3d.h"
  19. #include "video_core/renderer_vulkan/declarations.h"
  20. #include "video_core/renderer_vulkan/fixed_pipeline_state.h"
  21. #include "video_core/renderer_vulkan/maxwell_to_vk.h"
  22. #include "video_core/renderer_vulkan/renderer_vulkan.h"
  23. #include "video_core/renderer_vulkan/vk_buffer_cache.h"
  24. #include "video_core/renderer_vulkan/vk_compute_pass.h"
  25. #include "video_core/renderer_vulkan/vk_compute_pipeline.h"
  26. #include "video_core/renderer_vulkan/vk_descriptor_pool.h"
  27. #include "video_core/renderer_vulkan/vk_device.h"
  28. #include "video_core/renderer_vulkan/vk_graphics_pipeline.h"
  29. #include "video_core/renderer_vulkan/vk_pipeline_cache.h"
  30. #include "video_core/renderer_vulkan/vk_rasterizer.h"
  31. #include "video_core/renderer_vulkan/vk_renderpass_cache.h"
  32. #include "video_core/renderer_vulkan/vk_resource_manager.h"
  33. #include "video_core/renderer_vulkan/vk_sampler_cache.h"
  34. #include "video_core/renderer_vulkan/vk_scheduler.h"
  35. #include "video_core/renderer_vulkan/vk_staging_buffer_pool.h"
  36. #include "video_core/renderer_vulkan/vk_state_tracker.h"
  37. #include "video_core/renderer_vulkan/vk_texture_cache.h"
  38. #include "video_core/renderer_vulkan/vk_update_descriptor.h"
  39. namespace Vulkan {
  40. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  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_Geometry, "Vulkan", "Setup geometry", MP_RGB(192, 128, 128));
  46. MICROPROFILE_DEFINE(Vulkan_ConstBuffers, "Vulkan", "Setup constant buffers", MP_RGB(192, 128, 128));
  47. MICROPROFILE_DEFINE(Vulkan_GlobalBuffers, "Vulkan", "Setup global buffers", MP_RGB(192, 128, 128));
  48. MICROPROFILE_DEFINE(Vulkan_RenderTargets, "Vulkan", "Setup render targets", MP_RGB(192, 128, 128));
  49. MICROPROFILE_DEFINE(Vulkan_Textures, "Vulkan", "Setup textures", MP_RGB(192, 128, 128));
  50. MICROPROFILE_DEFINE(Vulkan_Images, "Vulkan", "Setup images", MP_RGB(192, 128, 128));
  51. MICROPROFILE_DEFINE(Vulkan_PipelineCache, "Vulkan", "Pipeline cache", MP_RGB(192, 128, 128));
  52. namespace {
  53. constexpr auto ComputeShaderIndex = static_cast<std::size_t>(Tegra::Engines::ShaderType::Compute);
  54. vk::Viewport GetViewportState(const VKDevice& device, const Maxwell& regs, std::size_t index) {
  55. const auto& viewport = regs.viewport_transform[index];
  56. const float x = viewport.translate_x - viewport.scale_x;
  57. const float y = viewport.translate_y - viewport.scale_y;
  58. const float width = viewport.scale_x * 2.0f;
  59. const float height = viewport.scale_y * 2.0f;
  60. const float reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne;
  61. float near = viewport.translate_z - viewport.scale_z * reduce_z;
  62. float far = viewport.translate_z + viewport.scale_z;
  63. if (!device.IsExtDepthRangeUnrestrictedSupported()) {
  64. near = std::clamp(near, 0.0f, 1.0f);
  65. far = std::clamp(far, 0.0f, 1.0f);
  66. }
  67. return vk::Viewport(x, y, width != 0 ? width : 1.0f, height != 0 ? height : 1.0f, near, far);
  68. }
  69. constexpr vk::Rect2D GetScissorState(const Maxwell& regs, std::size_t index) {
  70. const auto& scissor = regs.scissor_test[index];
  71. if (!scissor.enable) {
  72. return {{0, 0}, {INT32_MAX, INT32_MAX}};
  73. }
  74. const u32 width = scissor.max_x - scissor.min_x;
  75. const u32 height = scissor.max_y - scissor.min_y;
  76. return {{static_cast<s32>(scissor.min_x), static_cast<s32>(scissor.min_y)}, {width, height}};
  77. }
  78. std::array<GPUVAddr, Maxwell::MaxShaderProgram> GetShaderAddresses(
  79. const std::array<Shader, Maxwell::MaxShaderProgram>& shaders) {
  80. std::array<GPUVAddr, Maxwell::MaxShaderProgram> addresses;
  81. for (std::size_t i = 0; i < std::size(addresses); ++i) {
  82. addresses[i] = shaders[i] ? shaders[i]->GetGpuAddr() : 0;
  83. }
  84. return addresses;
  85. }
  86. void TransitionImages(const std::vector<ImageView>& views, vk::PipelineStageFlags pipeline_stage,
  87. vk::AccessFlags access) {
  88. for (auto& [view, layout] : views) {
  89. view->Transition(*layout, pipeline_stage, access);
  90. }
  91. }
  92. template <typename Engine, typename Entry>
  93. Tegra::Texture::FullTextureInfo GetTextureInfo(const Engine& engine, const Entry& entry,
  94. std::size_t stage, std::size_t index = 0) {
  95. const auto stage_type = static_cast<Tegra::Engines::ShaderType>(stage);
  96. if (entry.IsBindless()) {
  97. const Tegra::Texture::TextureHandle tex_handle =
  98. engine.AccessConstBuffer32(stage_type, entry.GetBuffer(), entry.GetOffset());
  99. return engine.GetTextureInfo(tex_handle);
  100. }
  101. const auto& gpu_profile = engine.AccessGuestDriverProfile();
  102. const u32 entry_offset = static_cast<u32>(index * gpu_profile.GetTextureHandlerSize());
  103. const u32 offset = entry.GetOffset() + entry_offset;
  104. if constexpr (std::is_same_v<Engine, Tegra::Engines::Maxwell3D>) {
  105. return engine.GetStageTexture(stage_type, offset);
  106. } else {
  107. return engine.GetTexture(offset);
  108. }
  109. }
  110. } // Anonymous namespace
  111. class BufferBindings final {
  112. public:
  113. void AddVertexBinding(const vk::Buffer* buffer, vk::DeviceSize offset) {
  114. vertex.buffer_ptrs[vertex.num_buffers] = buffer;
  115. vertex.offsets[vertex.num_buffers] = offset;
  116. ++vertex.num_buffers;
  117. }
  118. void SetIndexBinding(const vk::Buffer* buffer, vk::DeviceSize offset, vk::IndexType type) {
  119. index.buffer = buffer;
  120. index.offset = offset;
  121. index.type = type;
  122. }
  123. void Bind(VKScheduler& scheduler) const {
  124. // Use this large switch case to avoid dispatching more memory in the record lambda than
  125. // what we need. It looks horrible, but it's the best we can do on standard C++.
  126. switch (vertex.num_buffers) {
  127. case 0:
  128. return BindStatic<0>(scheduler);
  129. case 1:
  130. return BindStatic<1>(scheduler);
  131. case 2:
  132. return BindStatic<2>(scheduler);
  133. case 3:
  134. return BindStatic<3>(scheduler);
  135. case 4:
  136. return BindStatic<4>(scheduler);
  137. case 5:
  138. return BindStatic<5>(scheduler);
  139. case 6:
  140. return BindStatic<6>(scheduler);
  141. case 7:
  142. return BindStatic<7>(scheduler);
  143. case 8:
  144. return BindStatic<8>(scheduler);
  145. case 9:
  146. return BindStatic<9>(scheduler);
  147. case 10:
  148. return BindStatic<10>(scheduler);
  149. case 11:
  150. return BindStatic<11>(scheduler);
  151. case 12:
  152. return BindStatic<12>(scheduler);
  153. case 13:
  154. return BindStatic<13>(scheduler);
  155. case 14:
  156. return BindStatic<14>(scheduler);
  157. case 15:
  158. return BindStatic<15>(scheduler);
  159. case 16:
  160. return BindStatic<16>(scheduler);
  161. case 17:
  162. return BindStatic<17>(scheduler);
  163. case 18:
  164. return BindStatic<18>(scheduler);
  165. case 19:
  166. return BindStatic<19>(scheduler);
  167. case 20:
  168. return BindStatic<20>(scheduler);
  169. case 21:
  170. return BindStatic<21>(scheduler);
  171. case 22:
  172. return BindStatic<22>(scheduler);
  173. case 23:
  174. return BindStatic<23>(scheduler);
  175. case 24:
  176. return BindStatic<24>(scheduler);
  177. case 25:
  178. return BindStatic<25>(scheduler);
  179. case 26:
  180. return BindStatic<26>(scheduler);
  181. case 27:
  182. return BindStatic<27>(scheduler);
  183. case 28:
  184. return BindStatic<28>(scheduler);
  185. case 29:
  186. return BindStatic<29>(scheduler);
  187. case 30:
  188. return BindStatic<30>(scheduler);
  189. case 31:
  190. return BindStatic<31>(scheduler);
  191. case 32:
  192. return BindStatic<32>(scheduler);
  193. }
  194. UNREACHABLE();
  195. }
  196. private:
  197. // Some of these fields are intentionally left uninitialized to avoid initializing them twice.
  198. struct {
  199. std::size_t num_buffers = 0;
  200. std::array<const vk::Buffer*, Maxwell::NumVertexArrays> buffer_ptrs;
  201. std::array<vk::DeviceSize, Maxwell::NumVertexArrays> offsets;
  202. } vertex;
  203. struct {
  204. const vk::Buffer* buffer = nullptr;
  205. vk::DeviceSize offset;
  206. vk::IndexType type;
  207. } index;
  208. template <std::size_t N>
  209. void BindStatic(VKScheduler& scheduler) const {
  210. if (index.buffer != nullptr) {
  211. BindStatic<N, true>(scheduler);
  212. } else {
  213. BindStatic<N, false>(scheduler);
  214. }
  215. }
  216. template <std::size_t N, bool is_indexed>
  217. void BindStatic(VKScheduler& scheduler) const {
  218. static_assert(N <= Maxwell::NumVertexArrays);
  219. if constexpr (N == 0) {
  220. return;
  221. }
  222. std::array<vk::Buffer, N> buffers;
  223. std::transform(vertex.buffer_ptrs.begin(), vertex.buffer_ptrs.begin() + N, buffers.begin(),
  224. [](const auto ptr) { return *ptr; });
  225. std::array<vk::DeviceSize, N> offsets;
  226. std::copy(vertex.offsets.begin(), vertex.offsets.begin() + N, offsets.begin());
  227. if constexpr (is_indexed) {
  228. // Indexed draw
  229. scheduler.Record([buffers, offsets, index_buffer = *index.buffer,
  230. index_offset = index.offset,
  231. index_type = index.type](auto cmdbuf, auto& dld) {
  232. cmdbuf.bindIndexBuffer(index_buffer, index_offset, index_type, dld);
  233. cmdbuf.bindVertexBuffers(0, static_cast<u32>(N), buffers.data(), offsets.data(),
  234. dld);
  235. });
  236. } else {
  237. // Array draw
  238. scheduler.Record([buffers, offsets](auto cmdbuf, auto& dld) {
  239. cmdbuf.bindVertexBuffers(0, static_cast<u32>(N), buffers.data(), offsets.data(),
  240. dld);
  241. });
  242. }
  243. }
  244. };
  245. void RasterizerVulkan::DrawParameters::Draw(vk::CommandBuffer cmdbuf,
  246. const vk::DispatchLoaderDynamic& dld) const {
  247. if (is_indexed) {
  248. cmdbuf.drawIndexed(num_vertices, num_instances, 0, base_vertex, base_instance, dld);
  249. } else {
  250. cmdbuf.draw(num_vertices, num_instances, base_vertex, base_instance, dld);
  251. }
  252. }
  253. RasterizerVulkan::RasterizerVulkan(Core::System& system, Core::Frontend::EmuWindow& renderer,
  254. VKScreenInfo& screen_info, const VKDevice& device,
  255. VKResourceManager& resource_manager,
  256. VKMemoryManager& memory_manager, StateTracker& state_tracker,
  257. VKScheduler& scheduler)
  258. : RasterizerAccelerated{system.Memory()}, system{system}, render_window{renderer},
  259. screen_info{screen_info}, device{device}, resource_manager{resource_manager},
  260. memory_manager{memory_manager}, state_tracker{state_tracker}, scheduler{scheduler},
  261. staging_pool(device, memory_manager, scheduler), descriptor_pool(device),
  262. update_descriptor_queue(device, scheduler), renderpass_cache(device),
  263. quad_array_pass(device, scheduler, descriptor_pool, staging_pool, update_descriptor_queue),
  264. uint8_pass(device, scheduler, descriptor_pool, staging_pool, update_descriptor_queue),
  265. texture_cache(system, *this, device, resource_manager, memory_manager, scheduler,
  266. staging_pool),
  267. pipeline_cache(system, *this, device, scheduler, descriptor_pool, update_descriptor_queue,
  268. renderpass_cache),
  269. buffer_cache(*this, system, device, memory_manager, scheduler, staging_pool),
  270. sampler_cache(device), query_cache(system, *this, device, scheduler) {
  271. scheduler.SetQueryCache(query_cache);
  272. }
  273. RasterizerVulkan::~RasterizerVulkan() = default;
  274. void RasterizerVulkan::Draw(bool is_indexed, bool is_instanced) {
  275. MICROPROFILE_SCOPE(Vulkan_Drawing);
  276. FlushWork();
  277. query_cache.UpdateCounters();
  278. const auto& gpu = system.GPU().Maxwell3D();
  279. GraphicsPipelineCacheKey key{GetFixedPipelineState(gpu.regs)};
  280. buffer_cache.Map(CalculateGraphicsStreamBufferSize(is_indexed));
  281. BufferBindings buffer_bindings;
  282. const DrawParameters draw_params =
  283. SetupGeometry(key.fixed_state, buffer_bindings, is_indexed, is_instanced);
  284. update_descriptor_queue.Acquire();
  285. sampled_views.clear();
  286. image_views.clear();
  287. const auto shaders = pipeline_cache.GetShaders();
  288. key.shaders = GetShaderAddresses(shaders);
  289. SetupShaderDescriptors(shaders);
  290. buffer_cache.Unmap();
  291. const auto texceptions = UpdateAttachments();
  292. SetupImageTransitions(texceptions, color_attachments, zeta_attachment);
  293. key.renderpass_params = GetRenderPassParams(texceptions);
  294. auto& pipeline = pipeline_cache.GetGraphicsPipeline(key);
  295. scheduler.BindGraphicsPipeline(pipeline.GetHandle());
  296. const auto renderpass = pipeline.GetRenderPass();
  297. const auto [framebuffer, render_area] = ConfigureFramebuffers(renderpass);
  298. scheduler.RequestRenderpass({renderpass, framebuffer, {{0, 0}, render_area}, 0, nullptr});
  299. UpdateDynamicStates();
  300. buffer_bindings.Bind(scheduler);
  301. if (device.IsNvDeviceDiagnosticCheckpoints()) {
  302. scheduler.Record(
  303. [&pipeline](auto cmdbuf, auto& dld) { cmdbuf.setCheckpointNV(&pipeline, dld); });
  304. }
  305. BeginTransformFeedback();
  306. const auto pipeline_layout = pipeline.GetLayout();
  307. const auto descriptor_set = pipeline.CommitDescriptorSet();
  308. scheduler.Record([pipeline_layout, descriptor_set, draw_params](auto cmdbuf, auto& dld) {
  309. if (descriptor_set) {
  310. cmdbuf.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout,
  311. DESCRIPTOR_SET, 1, &descriptor_set, 0, nullptr, dld);
  312. }
  313. draw_params.Draw(cmdbuf, dld);
  314. });
  315. EndTransformFeedback();
  316. }
  317. void RasterizerVulkan::Clear() {
  318. MICROPROFILE_SCOPE(Vulkan_Clearing);
  319. const auto& gpu = system.GPU().Maxwell3D();
  320. if (!system.GPU().Maxwell3D().ShouldExecute()) {
  321. return;
  322. }
  323. sampled_views.clear();
  324. image_views.clear();
  325. query_cache.UpdateCounters();
  326. const auto& regs = gpu.regs;
  327. const bool use_color = regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  328. regs.clear_buffers.A;
  329. const bool use_depth = regs.clear_buffers.Z;
  330. const bool use_stencil = regs.clear_buffers.S;
  331. if (!use_color && !use_depth && !use_stencil) {
  332. return;
  333. }
  334. [[maybe_unused]] const auto texceptions = UpdateAttachments();
  335. DEBUG_ASSERT(texceptions.none());
  336. SetupImageTransitions(0, color_attachments, zeta_attachment);
  337. const vk::RenderPass renderpass = renderpass_cache.GetRenderPass(GetRenderPassParams(0));
  338. const auto [framebuffer, render_area] = ConfigureFramebuffers(renderpass);
  339. scheduler.RequestRenderpass({renderpass, framebuffer, {{0, 0}, render_area}, 0, nullptr});
  340. const auto& scissor = regs.scissor_test[0];
  341. const vk::Offset2D scissor_offset(scissor.min_x, scissor.min_y);
  342. vk::Extent2D scissor_extent{scissor.max_x - scissor.min_x, scissor.max_y - scissor.min_y};
  343. scissor_extent.width = std::min(scissor_extent.width, render_area.width);
  344. scissor_extent.height = std::min(scissor_extent.height, render_area.height);
  345. const u32 layer = regs.clear_buffers.layer;
  346. const vk::ClearRect clear_rect({scissor_offset, scissor_extent}, layer, 1);
  347. if (use_color) {
  348. const std::array clear_color = {regs.clear_color[0], regs.clear_color[1],
  349. regs.clear_color[2], regs.clear_color[3]};
  350. const vk::ClearValue clear_value{clear_color};
  351. const u32 color_attachment = regs.clear_buffers.RT;
  352. scheduler.Record([color_attachment, clear_value, clear_rect](auto cmdbuf, auto& dld) {
  353. const vk::ClearAttachment attachment(vk::ImageAspectFlagBits::eColor, color_attachment,
  354. clear_value);
  355. cmdbuf.clearAttachments(1, &attachment, 1, &clear_rect, dld);
  356. });
  357. }
  358. if (!use_depth && !use_stencil) {
  359. return;
  360. }
  361. vk::ImageAspectFlags aspect_flags;
  362. if (use_depth) {
  363. aspect_flags |= vk::ImageAspectFlagBits::eDepth;
  364. }
  365. if (use_stencil) {
  366. aspect_flags |= vk::ImageAspectFlagBits::eStencil;
  367. }
  368. scheduler.Record([clear_depth = regs.clear_depth, clear_stencil = regs.clear_stencil,
  369. clear_rect, aspect_flags](auto cmdbuf, auto& dld) {
  370. const vk::ClearDepthStencilValue clear_zeta(clear_depth, clear_stencil);
  371. const vk::ClearValue clear_value{clear_zeta};
  372. const vk::ClearAttachment attachment(aspect_flags, 0, clear_value);
  373. cmdbuf.clearAttachments(1, &attachment, 1, &clear_rect, dld);
  374. });
  375. }
  376. void RasterizerVulkan::DispatchCompute(GPUVAddr code_addr) {
  377. MICROPROFILE_SCOPE(Vulkan_Compute);
  378. update_descriptor_queue.Acquire();
  379. sampled_views.clear();
  380. image_views.clear();
  381. query_cache.UpdateCounters();
  382. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  383. const ComputePipelineCacheKey key{
  384. code_addr,
  385. launch_desc.shared_alloc,
  386. {launch_desc.block_dim_x, launch_desc.block_dim_y, launch_desc.block_dim_z}};
  387. auto& pipeline = pipeline_cache.GetComputePipeline(key);
  388. // Compute dispatches can't be executed inside a renderpass
  389. scheduler.RequestOutsideRenderPassOperationContext();
  390. buffer_cache.Map(CalculateComputeStreamBufferSize());
  391. const auto& entries = pipeline.GetEntries();
  392. SetupComputeConstBuffers(entries);
  393. SetupComputeGlobalBuffers(entries);
  394. SetupComputeTexelBuffers(entries);
  395. SetupComputeTextures(entries);
  396. SetupComputeImages(entries);
  397. buffer_cache.Unmap();
  398. TransitionImages(sampled_views, vk::PipelineStageFlagBits::eComputeShader,
  399. vk::AccessFlagBits::eShaderRead);
  400. TransitionImages(image_views, vk::PipelineStageFlagBits::eComputeShader,
  401. vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite);
  402. if (device.IsNvDeviceDiagnosticCheckpoints()) {
  403. scheduler.Record(
  404. [&pipeline](auto cmdbuf, auto& dld) { cmdbuf.setCheckpointNV(nullptr, dld); });
  405. }
  406. scheduler.Record([grid_x = launch_desc.grid_dim_x, grid_y = launch_desc.grid_dim_y,
  407. grid_z = launch_desc.grid_dim_z, pipeline_handle = pipeline.GetHandle(),
  408. layout = pipeline.GetLayout(),
  409. descriptor_set = pipeline.CommitDescriptorSet()](auto cmdbuf, auto& dld) {
  410. cmdbuf.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline_handle, dld);
  411. cmdbuf.bindDescriptorSets(vk::PipelineBindPoint::eCompute, layout, DESCRIPTOR_SET, 1,
  412. &descriptor_set, 0, nullptr, dld);
  413. cmdbuf.dispatch(grid_x, grid_y, grid_z, dld);
  414. });
  415. }
  416. void RasterizerVulkan::ResetCounter(VideoCore::QueryType type) {
  417. query_cache.ResetCounter(type);
  418. }
  419. void RasterizerVulkan::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  420. std::optional<u64> timestamp) {
  421. query_cache.Query(gpu_addr, type, timestamp);
  422. }
  423. void RasterizerVulkan::FlushAll() {}
  424. void RasterizerVulkan::FlushRegion(VAddr addr, u64 size) {
  425. if (addr == 0 || size == 0) {
  426. return;
  427. }
  428. texture_cache.FlushRegion(addr, size);
  429. buffer_cache.FlushRegion(addr, size);
  430. query_cache.FlushRegion(addr, size);
  431. }
  432. void RasterizerVulkan::InvalidateRegion(VAddr addr, u64 size) {
  433. if (addr == 0 || size == 0) {
  434. return;
  435. }
  436. texture_cache.InvalidateRegion(addr, size);
  437. pipeline_cache.InvalidateRegion(addr, size);
  438. buffer_cache.InvalidateRegion(addr, size);
  439. query_cache.InvalidateRegion(addr, size);
  440. }
  441. void RasterizerVulkan::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  442. FlushRegion(addr, size);
  443. InvalidateRegion(addr, size);
  444. }
  445. void RasterizerVulkan::FlushCommands() {
  446. if (draw_counter > 0) {
  447. draw_counter = 0;
  448. scheduler.Flush();
  449. }
  450. }
  451. void RasterizerVulkan::TickFrame() {
  452. draw_counter = 0;
  453. update_descriptor_queue.TickFrame();
  454. buffer_cache.TickFrame();
  455. staging_pool.TickFrame();
  456. }
  457. bool RasterizerVulkan::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  458. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  459. const Tegra::Engines::Fermi2D::Config& copy_config) {
  460. texture_cache.DoFermiCopy(src, dst, copy_config);
  461. return true;
  462. }
  463. bool RasterizerVulkan::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  464. VAddr framebuffer_addr, u32 pixel_stride) {
  465. if (!framebuffer_addr) {
  466. return false;
  467. }
  468. const auto surface{texture_cache.TryFindFramebufferSurface(framebuffer_addr)};
  469. if (!surface) {
  470. return false;
  471. }
  472. // Verify that the cached surface is the same size and format as the requested framebuffer
  473. const auto& params{surface->GetSurfaceParams()};
  474. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  475. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  476. screen_info.image = &surface->GetImage();
  477. screen_info.width = params.width;
  478. screen_info.height = params.height;
  479. screen_info.is_srgb = surface->GetSurfaceParams().srgb_conversion;
  480. return true;
  481. }
  482. void RasterizerVulkan::SetupDirtyFlags() {
  483. state_tracker.Initialize();
  484. }
  485. void RasterizerVulkan::FlushWork() {
  486. static constexpr u32 DRAWS_TO_DISPATCH = 4096;
  487. // Only check multiples of 8 draws
  488. static_assert(DRAWS_TO_DISPATCH % 8 == 0);
  489. if ((++draw_counter & 7) != 7) {
  490. return;
  491. }
  492. if (draw_counter < DRAWS_TO_DISPATCH) {
  493. // Send recorded tasks to the worker thread
  494. scheduler.DispatchWork();
  495. return;
  496. }
  497. // Otherwise (every certain number of draws) flush execution.
  498. // This submits commands to the Vulkan driver.
  499. scheduler.Flush();
  500. draw_counter = 0;
  501. }
  502. RasterizerVulkan::Texceptions RasterizerVulkan::UpdateAttachments() {
  503. MICROPROFILE_SCOPE(Vulkan_RenderTargets);
  504. auto& dirty = system.GPU().Maxwell3D().dirty.flags;
  505. const bool update_rendertargets = dirty[VideoCommon::Dirty::RenderTargets];
  506. dirty[VideoCommon::Dirty::RenderTargets] = false;
  507. texture_cache.GuardRenderTargets(true);
  508. Texceptions texceptions;
  509. for (std::size_t rt = 0; rt < Maxwell::NumRenderTargets; ++rt) {
  510. if (update_rendertargets) {
  511. color_attachments[rt] = texture_cache.GetColorBufferSurface(rt);
  512. }
  513. if (color_attachments[rt] && WalkAttachmentOverlaps(*color_attachments[rt])) {
  514. texceptions[rt] = true;
  515. }
  516. }
  517. if (update_rendertargets) {
  518. zeta_attachment = texture_cache.GetDepthBufferSurface();
  519. }
  520. if (zeta_attachment && WalkAttachmentOverlaps(*zeta_attachment)) {
  521. texceptions[ZETA_TEXCEPTION_INDEX] = true;
  522. }
  523. texture_cache.GuardRenderTargets(false);
  524. return texceptions;
  525. }
  526. bool RasterizerVulkan::WalkAttachmentOverlaps(const CachedSurfaceView& attachment) {
  527. bool overlap = false;
  528. for (auto& [view, layout] : sampled_views) {
  529. if (!attachment.IsSameSurface(*view)) {
  530. continue;
  531. }
  532. overlap = true;
  533. *layout = vk::ImageLayout::eGeneral;
  534. }
  535. return overlap;
  536. }
  537. std::tuple<vk::Framebuffer, vk::Extent2D> RasterizerVulkan::ConfigureFramebuffers(
  538. vk::RenderPass renderpass) {
  539. FramebufferCacheKey key{renderpass, std::numeric_limits<u32>::max(),
  540. std::numeric_limits<u32>::max(), std::numeric_limits<u32>::max()};
  541. const auto try_push = [&](const View& view) {
  542. if (!view) {
  543. return false;
  544. }
  545. key.views.push_back(view->GetHandle());
  546. key.width = std::min(key.width, view->GetWidth());
  547. key.height = std::min(key.height, view->GetHeight());
  548. key.layers = std::min(key.layers, view->GetNumLayers());
  549. return true;
  550. };
  551. for (std::size_t index = 0; index < std::size(color_attachments); ++index) {
  552. if (try_push(color_attachments[index])) {
  553. texture_cache.MarkColorBufferInUse(index);
  554. }
  555. }
  556. if (try_push(zeta_attachment)) {
  557. texture_cache.MarkDepthBufferInUse();
  558. }
  559. const auto [fbentry, is_cache_miss] = framebuffer_cache.try_emplace(key);
  560. auto& framebuffer = fbentry->second;
  561. if (is_cache_miss) {
  562. const vk::FramebufferCreateInfo framebuffer_ci(
  563. {}, key.renderpass, static_cast<u32>(key.views.size()), key.views.data(), key.width,
  564. key.height, key.layers);
  565. const auto dev = device.GetLogical();
  566. const auto& dld = device.GetDispatchLoader();
  567. framebuffer = dev.createFramebufferUnique(framebuffer_ci, nullptr, dld);
  568. }
  569. return {*framebuffer, vk::Extent2D{key.width, key.height}};
  570. }
  571. RasterizerVulkan::DrawParameters RasterizerVulkan::SetupGeometry(FixedPipelineState& fixed_state,
  572. BufferBindings& buffer_bindings,
  573. bool is_indexed,
  574. bool is_instanced) {
  575. MICROPROFILE_SCOPE(Vulkan_Geometry);
  576. const auto& gpu = system.GPU().Maxwell3D();
  577. const auto& regs = gpu.regs;
  578. SetupVertexArrays(fixed_state.vertex_input, buffer_bindings);
  579. const u32 base_instance = regs.vb_base_instance;
  580. const u32 num_instances = is_instanced ? gpu.mme_draw.instance_count : 1;
  581. const u32 base_vertex = is_indexed ? regs.vb_element_base : regs.vertex_buffer.first;
  582. const u32 num_vertices = is_indexed ? regs.index_array.count : regs.vertex_buffer.count;
  583. DrawParameters params{base_instance, num_instances, base_vertex, num_vertices, is_indexed};
  584. SetupIndexBuffer(buffer_bindings, params, is_indexed);
  585. return params;
  586. }
  587. void RasterizerVulkan::SetupShaderDescriptors(
  588. const std::array<Shader, Maxwell::MaxShaderProgram>& shaders) {
  589. texture_cache.GuardSamplers(true);
  590. for (std::size_t stage = 0; stage < Maxwell::MaxShaderStage; ++stage) {
  591. // Skip VertexA stage
  592. const auto& shader = shaders[stage + 1];
  593. if (!shader) {
  594. continue;
  595. }
  596. const auto& entries = shader->GetEntries();
  597. SetupGraphicsConstBuffers(entries, stage);
  598. SetupGraphicsGlobalBuffers(entries, stage);
  599. SetupGraphicsTexelBuffers(entries, stage);
  600. SetupGraphicsTextures(entries, stage);
  601. SetupGraphicsImages(entries, stage);
  602. }
  603. texture_cache.GuardSamplers(false);
  604. }
  605. void RasterizerVulkan::SetupImageTransitions(
  606. Texceptions texceptions, const std::array<View, Maxwell::NumRenderTargets>& color_attachments,
  607. const View& zeta_attachment) {
  608. TransitionImages(sampled_views, vk::PipelineStageFlagBits::eAllGraphics,
  609. vk::AccessFlagBits::eShaderRead);
  610. TransitionImages(image_views, vk::PipelineStageFlagBits::eAllGraphics,
  611. vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite);
  612. for (std::size_t rt = 0; rt < std::size(color_attachments); ++rt) {
  613. const auto color_attachment = color_attachments[rt];
  614. if (color_attachment == nullptr) {
  615. continue;
  616. }
  617. const auto image_layout =
  618. texceptions[rt] ? vk::ImageLayout::eGeneral : vk::ImageLayout::eColorAttachmentOptimal;
  619. color_attachment->Transition(
  620. image_layout, vk::PipelineStageFlagBits::eColorAttachmentOutput,
  621. vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite);
  622. }
  623. if (zeta_attachment != nullptr) {
  624. const auto image_layout = texceptions[ZETA_TEXCEPTION_INDEX]
  625. ? vk::ImageLayout::eGeneral
  626. : vk::ImageLayout::eDepthStencilAttachmentOptimal;
  627. zeta_attachment->Transition(image_layout, vk::PipelineStageFlagBits::eLateFragmentTests,
  628. vk::AccessFlagBits::eDepthStencilAttachmentRead |
  629. vk::AccessFlagBits::eDepthStencilAttachmentWrite);
  630. }
  631. }
  632. void RasterizerVulkan::UpdateDynamicStates() {
  633. auto& regs = system.GPU().Maxwell3D().regs;
  634. UpdateViewportsState(regs);
  635. UpdateScissorsState(regs);
  636. UpdateDepthBias(regs);
  637. UpdateBlendConstants(regs);
  638. UpdateDepthBounds(regs);
  639. UpdateStencilFaces(regs);
  640. }
  641. void RasterizerVulkan::BeginTransformFeedback() {
  642. const auto& regs = system.GPU().Maxwell3D().regs;
  643. if (regs.tfb_enabled == 0) {
  644. return;
  645. }
  646. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationControl) ||
  647. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationEval) ||
  648. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::Geometry));
  649. UNIMPLEMENTED_IF(regs.tfb_bindings[1].buffer_enable);
  650. UNIMPLEMENTED_IF(regs.tfb_bindings[2].buffer_enable);
  651. UNIMPLEMENTED_IF(regs.tfb_bindings[3].buffer_enable);
  652. const auto& binding = regs.tfb_bindings[0];
  653. UNIMPLEMENTED_IF(binding.buffer_enable == 0);
  654. UNIMPLEMENTED_IF(binding.buffer_offset != 0);
  655. const GPUVAddr gpu_addr = binding.Address();
  656. const std::size_t size = binding.buffer_size;
  657. const auto [buffer, offset] = buffer_cache.UploadMemory(gpu_addr, size, 4, true);
  658. scheduler.Record([buffer = *buffer, offset = offset, size](auto cmdbuf, auto& dld) {
  659. cmdbuf.bindTransformFeedbackBuffersEXT(0, {buffer}, {offset}, {size}, dld);
  660. cmdbuf.beginTransformFeedbackEXT(0, {}, {}, dld);
  661. });
  662. }
  663. void RasterizerVulkan::EndTransformFeedback() {
  664. const auto& regs = system.GPU().Maxwell3D().regs;
  665. if (regs.tfb_enabled == 0) {
  666. return;
  667. }
  668. scheduler.Record(
  669. [](auto cmdbuf, auto& dld) { cmdbuf.endTransformFeedbackEXT(0, {}, {}, dld); });
  670. }
  671. void RasterizerVulkan::SetupVertexArrays(FixedPipelineState::VertexInput& vertex_input,
  672. BufferBindings& buffer_bindings) {
  673. const auto& regs = system.GPU().Maxwell3D().regs;
  674. for (u32 index = 0; index < static_cast<u32>(Maxwell::NumVertexAttributes); ++index) {
  675. const auto& attrib = regs.vertex_attrib_format[index];
  676. if (!attrib.IsValid()) {
  677. continue;
  678. }
  679. const auto& buffer = regs.vertex_array[attrib.buffer];
  680. ASSERT(buffer.IsEnabled());
  681. vertex_input.attributes[vertex_input.num_attributes++] =
  682. FixedPipelineState::VertexAttribute(index, attrib.buffer, attrib.type, attrib.size,
  683. attrib.offset);
  684. }
  685. for (u32 index = 0; index < static_cast<u32>(Maxwell::NumVertexArrays); ++index) {
  686. const auto& vertex_array = regs.vertex_array[index];
  687. if (!vertex_array.IsEnabled()) {
  688. continue;
  689. }
  690. const GPUVAddr start{vertex_array.StartAddress()};
  691. const GPUVAddr end{regs.vertex_array_limit[index].LimitAddress()};
  692. ASSERT(end > start);
  693. const std::size_t size{end - start + 1};
  694. const auto [buffer, offset] = buffer_cache.UploadMemory(start, size);
  695. vertex_input.bindings[vertex_input.num_bindings++] = FixedPipelineState::VertexBinding(
  696. index, vertex_array.stride,
  697. regs.instanced_arrays.IsInstancingEnabled(index) ? vertex_array.divisor : 0);
  698. buffer_bindings.AddVertexBinding(buffer, offset);
  699. }
  700. }
  701. void RasterizerVulkan::SetupIndexBuffer(BufferBindings& buffer_bindings, DrawParameters& params,
  702. bool is_indexed) {
  703. const auto& regs = system.GPU().Maxwell3D().regs;
  704. switch (regs.draw.topology) {
  705. case Maxwell::PrimitiveTopology::Quads:
  706. if (params.is_indexed) {
  707. UNIMPLEMENTED();
  708. } else {
  709. const auto [buffer, offset] =
  710. quad_array_pass.Assemble(params.num_vertices, params.base_vertex);
  711. buffer_bindings.SetIndexBinding(&buffer, offset, vk::IndexType::eUint32);
  712. params.base_vertex = 0;
  713. params.num_vertices = params.num_vertices * 6 / 4;
  714. params.is_indexed = true;
  715. }
  716. break;
  717. default: {
  718. if (!is_indexed) {
  719. break;
  720. }
  721. const GPUVAddr gpu_addr = regs.index_array.IndexStart();
  722. auto [buffer, offset] = buffer_cache.UploadMemory(gpu_addr, CalculateIndexBufferSize());
  723. auto format = regs.index_array.format;
  724. const bool is_uint8 = format == Maxwell::IndexFormat::UnsignedByte;
  725. if (is_uint8 && !device.IsExtIndexTypeUint8Supported()) {
  726. std::tie(buffer, offset) = uint8_pass.Assemble(params.num_vertices, *buffer, offset);
  727. format = Maxwell::IndexFormat::UnsignedShort;
  728. }
  729. buffer_bindings.SetIndexBinding(buffer, offset, MaxwellToVK::IndexFormat(device, format));
  730. break;
  731. }
  732. }
  733. }
  734. void RasterizerVulkan::SetupGraphicsConstBuffers(const ShaderEntries& entries, std::size_t stage) {
  735. MICROPROFILE_SCOPE(Vulkan_ConstBuffers);
  736. const auto& gpu = system.GPU().Maxwell3D();
  737. const auto& shader_stage = gpu.state.shader_stages[stage];
  738. for (const auto& entry : entries.const_buffers) {
  739. SetupConstBuffer(entry, shader_stage.const_buffers[entry.GetIndex()]);
  740. }
  741. }
  742. void RasterizerVulkan::SetupGraphicsGlobalBuffers(const ShaderEntries& entries, std::size_t stage) {
  743. MICROPROFILE_SCOPE(Vulkan_GlobalBuffers);
  744. auto& gpu{system.GPU()};
  745. const auto cbufs{gpu.Maxwell3D().state.shader_stages[stage]};
  746. for (const auto& entry : entries.global_buffers) {
  747. const auto addr = cbufs.const_buffers[entry.GetCbufIndex()].address + entry.GetCbufOffset();
  748. SetupGlobalBuffer(entry, addr);
  749. }
  750. }
  751. void RasterizerVulkan::SetupGraphicsTexelBuffers(const ShaderEntries& entries, std::size_t stage) {
  752. MICROPROFILE_SCOPE(Vulkan_Textures);
  753. const auto& gpu = system.GPU().Maxwell3D();
  754. for (const auto& entry : entries.texel_buffers) {
  755. const auto image = GetTextureInfo(gpu, entry, stage).tic;
  756. SetupTexelBuffer(image, entry);
  757. }
  758. }
  759. void RasterizerVulkan::SetupGraphicsTextures(const ShaderEntries& entries, std::size_t stage) {
  760. MICROPROFILE_SCOPE(Vulkan_Textures);
  761. const auto& gpu = system.GPU().Maxwell3D();
  762. for (const auto& entry : entries.samplers) {
  763. for (std::size_t i = 0; i < entry.Size(); ++i) {
  764. const auto texture = GetTextureInfo(gpu, entry, stage, i);
  765. SetupTexture(texture, entry);
  766. }
  767. }
  768. }
  769. void RasterizerVulkan::SetupGraphicsImages(const ShaderEntries& entries, std::size_t stage) {
  770. MICROPROFILE_SCOPE(Vulkan_Images);
  771. const auto& gpu = system.GPU().Maxwell3D();
  772. for (const auto& entry : entries.images) {
  773. const auto tic = GetTextureInfo(gpu, entry, stage).tic;
  774. SetupImage(tic, entry);
  775. }
  776. }
  777. void RasterizerVulkan::SetupComputeConstBuffers(const ShaderEntries& entries) {
  778. MICROPROFILE_SCOPE(Vulkan_ConstBuffers);
  779. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  780. for (const auto& entry : entries.const_buffers) {
  781. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  782. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  783. Tegra::Engines::ConstBufferInfo buffer;
  784. buffer.address = config.Address();
  785. buffer.size = config.size;
  786. buffer.enabled = mask[entry.GetIndex()];
  787. SetupConstBuffer(entry, buffer);
  788. }
  789. }
  790. void RasterizerVulkan::SetupComputeGlobalBuffers(const ShaderEntries& entries) {
  791. MICROPROFILE_SCOPE(Vulkan_GlobalBuffers);
  792. const auto cbufs{system.GPU().KeplerCompute().launch_description.const_buffer_config};
  793. for (const auto& entry : entries.global_buffers) {
  794. const auto addr{cbufs[entry.GetCbufIndex()].Address() + entry.GetCbufOffset()};
  795. SetupGlobalBuffer(entry, addr);
  796. }
  797. }
  798. void RasterizerVulkan::SetupComputeTexelBuffers(const ShaderEntries& entries) {
  799. MICROPROFILE_SCOPE(Vulkan_Textures);
  800. const auto& gpu = system.GPU().KeplerCompute();
  801. for (const auto& entry : entries.texel_buffers) {
  802. const auto image = GetTextureInfo(gpu, entry, ComputeShaderIndex).tic;
  803. SetupTexelBuffer(image, entry);
  804. }
  805. }
  806. void RasterizerVulkan::SetupComputeTextures(const ShaderEntries& entries) {
  807. MICROPROFILE_SCOPE(Vulkan_Textures);
  808. const auto& gpu = system.GPU().KeplerCompute();
  809. for (const auto& entry : entries.samplers) {
  810. for (std::size_t i = 0; i < entry.Size(); ++i) {
  811. const auto texture = GetTextureInfo(gpu, entry, ComputeShaderIndex, i);
  812. SetupTexture(texture, entry);
  813. }
  814. }
  815. }
  816. void RasterizerVulkan::SetupComputeImages(const ShaderEntries& entries) {
  817. MICROPROFILE_SCOPE(Vulkan_Images);
  818. const auto& gpu = system.GPU().KeplerCompute();
  819. for (const auto& entry : entries.images) {
  820. const auto tic = GetTextureInfo(gpu, entry, ComputeShaderIndex).tic;
  821. SetupImage(tic, entry);
  822. }
  823. }
  824. void RasterizerVulkan::SetupConstBuffer(const ConstBufferEntry& entry,
  825. const Tegra::Engines::ConstBufferInfo& buffer) {
  826. if (!buffer.enabled) {
  827. // Set values to zero to unbind buffers
  828. update_descriptor_queue.AddBuffer(buffer_cache.GetEmptyBuffer(sizeof(float)), 0,
  829. sizeof(float));
  830. return;
  831. }
  832. // Align the size to avoid bad std140 interactions
  833. const std::size_t size =
  834. Common::AlignUp(CalculateConstBufferSize(entry, buffer), 4 * sizeof(float));
  835. ASSERT(size <= MaxConstbufferSize);
  836. const auto [buffer_handle, offset] =
  837. buffer_cache.UploadMemory(buffer.address, size, device.GetUniformBufferAlignment());
  838. update_descriptor_queue.AddBuffer(buffer_handle, offset, size);
  839. }
  840. void RasterizerVulkan::SetupGlobalBuffer(const GlobalBufferEntry& entry, GPUVAddr address) {
  841. auto& memory_manager{system.GPU().MemoryManager()};
  842. const auto actual_addr = memory_manager.Read<u64>(address);
  843. const auto size = memory_manager.Read<u32>(address + 8);
  844. if (size == 0) {
  845. // Sometimes global memory pointers don't have a proper size. Upload a dummy entry because
  846. // Vulkan doesn't like empty buffers.
  847. constexpr std::size_t dummy_size = 4;
  848. const auto buffer = buffer_cache.GetEmptyBuffer(dummy_size);
  849. update_descriptor_queue.AddBuffer(buffer, 0, dummy_size);
  850. return;
  851. }
  852. const auto [buffer, offset] = buffer_cache.UploadMemory(
  853. actual_addr, size, device.GetStorageBufferAlignment(), entry.IsWritten());
  854. update_descriptor_queue.AddBuffer(buffer, offset, size);
  855. }
  856. void RasterizerVulkan::SetupTexelBuffer(const Tegra::Texture::TICEntry& tic,
  857. const TexelBufferEntry& entry) {
  858. const auto view = texture_cache.GetTextureSurface(tic, entry);
  859. ASSERT(view->IsBufferView());
  860. update_descriptor_queue.AddTexelBuffer(view->GetBufferView());
  861. }
  862. void RasterizerVulkan::SetupTexture(const Tegra::Texture::FullTextureInfo& texture,
  863. const SamplerEntry& entry) {
  864. auto view = texture_cache.GetTextureSurface(texture.tic, entry);
  865. ASSERT(!view->IsBufferView());
  866. const auto image_view = view->GetHandle(texture.tic.x_source, texture.tic.y_source,
  867. texture.tic.z_source, texture.tic.w_source);
  868. const auto sampler = sampler_cache.GetSampler(texture.tsc);
  869. update_descriptor_queue.AddSampledImage(sampler, image_view);
  870. const auto image_layout = update_descriptor_queue.GetLastImageLayout();
  871. *image_layout = vk::ImageLayout::eShaderReadOnlyOptimal;
  872. sampled_views.push_back(ImageView{std::move(view), image_layout});
  873. }
  874. void RasterizerVulkan::SetupImage(const Tegra::Texture::TICEntry& tic, const ImageEntry& entry) {
  875. auto view = texture_cache.GetImageSurface(tic, entry);
  876. if (entry.IsWritten()) {
  877. view->MarkAsModified(texture_cache.Tick());
  878. }
  879. UNIMPLEMENTED_IF(tic.IsBuffer());
  880. const auto image_view = view->GetHandle(tic.x_source, tic.y_source, tic.z_source, tic.w_source);
  881. update_descriptor_queue.AddImage(image_view);
  882. const auto image_layout = update_descriptor_queue.GetLastImageLayout();
  883. *image_layout = vk::ImageLayout::eGeneral;
  884. image_views.push_back(ImageView{std::move(view), image_layout});
  885. }
  886. void RasterizerVulkan::UpdateViewportsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  887. if (!state_tracker.TouchViewports()) {
  888. return;
  889. }
  890. const std::array viewports{
  891. GetViewportState(device, regs, 0), GetViewportState(device, regs, 1),
  892. GetViewportState(device, regs, 2), GetViewportState(device, regs, 3),
  893. GetViewportState(device, regs, 4), GetViewportState(device, regs, 5),
  894. GetViewportState(device, regs, 6), GetViewportState(device, regs, 7),
  895. GetViewportState(device, regs, 8), GetViewportState(device, regs, 9),
  896. GetViewportState(device, regs, 10), GetViewportState(device, regs, 11),
  897. GetViewportState(device, regs, 12), GetViewportState(device, regs, 13),
  898. GetViewportState(device, regs, 14), GetViewportState(device, regs, 15)};
  899. scheduler.Record([viewports](auto cmdbuf, auto& dld) {
  900. cmdbuf.setViewport(0, static_cast<u32>(viewports.size()), viewports.data(), dld);
  901. });
  902. }
  903. void RasterizerVulkan::UpdateScissorsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  904. if (!state_tracker.TouchScissors()) {
  905. return;
  906. }
  907. const std::array scissors = {
  908. GetScissorState(regs, 0), GetScissorState(regs, 1), GetScissorState(regs, 2),
  909. GetScissorState(regs, 3), GetScissorState(regs, 4), GetScissorState(regs, 5),
  910. GetScissorState(regs, 6), GetScissorState(regs, 7), GetScissorState(regs, 8),
  911. GetScissorState(regs, 9), GetScissorState(regs, 10), GetScissorState(regs, 11),
  912. GetScissorState(regs, 12), GetScissorState(regs, 13), GetScissorState(regs, 14),
  913. GetScissorState(regs, 15)};
  914. scheduler.Record([scissors](auto cmdbuf, auto& dld) {
  915. cmdbuf.setScissor(0, static_cast<u32>(scissors.size()), scissors.data(), dld);
  916. });
  917. }
  918. void RasterizerVulkan::UpdateDepthBias(Tegra::Engines::Maxwell3D::Regs& regs) {
  919. if (!state_tracker.TouchDepthBias()) {
  920. return;
  921. }
  922. scheduler.Record([constant = regs.polygon_offset_units, clamp = regs.polygon_offset_clamp,
  923. factor = regs.polygon_offset_factor](auto cmdbuf, auto& dld) {
  924. cmdbuf.setDepthBias(constant, clamp, factor / 2.0f, dld);
  925. });
  926. }
  927. void RasterizerVulkan::UpdateBlendConstants(Tegra::Engines::Maxwell3D::Regs& regs) {
  928. if (!state_tracker.TouchBlendConstants()) {
  929. return;
  930. }
  931. const std::array blend_color = {regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  932. regs.blend_color.a};
  933. scheduler.Record([blend_color](auto cmdbuf, auto& dld) {
  934. cmdbuf.setBlendConstants(blend_color.data(), dld);
  935. });
  936. }
  937. void RasterizerVulkan::UpdateDepthBounds(Tegra::Engines::Maxwell3D::Regs& regs) {
  938. if (!state_tracker.TouchDepthBounds()) {
  939. return;
  940. }
  941. scheduler.Record([min = regs.depth_bounds[0], max = regs.depth_bounds[1]](
  942. auto cmdbuf, auto& dld) { cmdbuf.setDepthBounds(min, max, dld); });
  943. }
  944. void RasterizerVulkan::UpdateStencilFaces(Tegra::Engines::Maxwell3D::Regs& regs) {
  945. if (!state_tracker.TouchStencilProperties()) {
  946. return;
  947. }
  948. if (regs.stencil_two_side_enable) {
  949. // Separate values per face
  950. scheduler.Record(
  951. [front_ref = regs.stencil_front_func_ref, front_write_mask = regs.stencil_front_mask,
  952. front_test_mask = regs.stencil_front_func_mask, back_ref = regs.stencil_back_func_ref,
  953. back_write_mask = regs.stencil_back_mask,
  954. back_test_mask = regs.stencil_back_func_mask](auto cmdbuf, auto& dld) {
  955. // Front face
  956. cmdbuf.setStencilReference(vk::StencilFaceFlagBits::eFront, front_ref, dld);
  957. cmdbuf.setStencilWriteMask(vk::StencilFaceFlagBits::eFront, front_write_mask, dld);
  958. cmdbuf.setStencilCompareMask(vk::StencilFaceFlagBits::eFront, front_test_mask, dld);
  959. // Back face
  960. cmdbuf.setStencilReference(vk::StencilFaceFlagBits::eBack, back_ref, dld);
  961. cmdbuf.setStencilWriteMask(vk::StencilFaceFlagBits::eBack, back_write_mask, dld);
  962. cmdbuf.setStencilCompareMask(vk::StencilFaceFlagBits::eBack, back_test_mask, dld);
  963. });
  964. } else {
  965. // Front face defines both faces
  966. scheduler.Record([ref = regs.stencil_back_func_ref, write_mask = regs.stencil_back_mask,
  967. test_mask = regs.stencil_back_func_mask](auto cmdbuf, auto& dld) {
  968. cmdbuf.setStencilReference(vk::StencilFaceFlagBits::eFrontAndBack, ref, dld);
  969. cmdbuf.setStencilWriteMask(vk::StencilFaceFlagBits::eFrontAndBack, write_mask, dld);
  970. cmdbuf.setStencilCompareMask(vk::StencilFaceFlagBits::eFrontAndBack, test_mask, dld);
  971. });
  972. }
  973. }
  974. std::size_t RasterizerVulkan::CalculateGraphicsStreamBufferSize(bool is_indexed) const {
  975. std::size_t size = CalculateVertexArraysSize();
  976. if (is_indexed) {
  977. size = Common::AlignUp(size, 4) + CalculateIndexBufferSize();
  978. }
  979. size += Maxwell::MaxConstBuffers * (MaxConstbufferSize + device.GetUniformBufferAlignment());
  980. return size;
  981. }
  982. std::size_t RasterizerVulkan::CalculateComputeStreamBufferSize() const {
  983. return Tegra::Engines::KeplerCompute::NumConstBuffers *
  984. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  985. }
  986. std::size_t RasterizerVulkan::CalculateVertexArraysSize() const {
  987. const auto& regs = system.GPU().Maxwell3D().regs;
  988. std::size_t size = 0;
  989. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  990. // This implementation assumes that all attributes are used in the shader.
  991. const GPUVAddr start{regs.vertex_array[index].StartAddress()};
  992. const GPUVAddr end{regs.vertex_array_limit[index].LimitAddress()};
  993. DEBUG_ASSERT(end >= start);
  994. size += (end - start + 1) * regs.vertex_array[index].enable;
  995. }
  996. return size;
  997. }
  998. std::size_t RasterizerVulkan::CalculateIndexBufferSize() const {
  999. const auto& regs = system.GPU().Maxwell3D().regs;
  1000. return static_cast<std::size_t>(regs.index_array.count) *
  1001. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  1002. }
  1003. std::size_t RasterizerVulkan::CalculateConstBufferSize(
  1004. const ConstBufferEntry& entry, const Tegra::Engines::ConstBufferInfo& buffer) const {
  1005. if (entry.IsIndirect()) {
  1006. // Buffer is accessed indirectly, so upload the entire thing
  1007. return buffer.size;
  1008. } else {
  1009. // Buffer is accessed directly, upload just what we use
  1010. return entry.GetSize();
  1011. }
  1012. }
  1013. RenderPassParams RasterizerVulkan::GetRenderPassParams(Texceptions texceptions) const {
  1014. using namespace VideoCore::Surface;
  1015. const auto& regs = system.GPU().Maxwell3D().regs;
  1016. RenderPassParams renderpass_params;
  1017. for (std::size_t rt = 0; rt < static_cast<std::size_t>(regs.rt_control.count); ++rt) {
  1018. const auto& rendertarget = regs.rt[rt];
  1019. if (rendertarget.Address() == 0 || rendertarget.format == Tegra::RenderTargetFormat::NONE) {
  1020. continue;
  1021. }
  1022. renderpass_params.color_attachments.push_back(RenderPassParams::ColorAttachment{
  1023. static_cast<u32>(rt), PixelFormatFromRenderTargetFormat(rendertarget.format),
  1024. texceptions[rt]});
  1025. }
  1026. renderpass_params.has_zeta = regs.zeta_enable;
  1027. if (renderpass_params.has_zeta) {
  1028. renderpass_params.zeta_pixel_format = PixelFormatFromDepthFormat(regs.zeta.format);
  1029. renderpass_params.zeta_texception = texceptions[ZETA_TEXCEPTION_INDEX];
  1030. }
  1031. return renderpass_params;
  1032. }
  1033. } // namespace Vulkan