vk_rasterizer.cpp 52 KB

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