vk_rasterizer.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  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 || !size) {
  426. return;
  427. }
  428. CacheAddr cache_addr = ToCacheAddr(system.Memory().GetPointer(addr));
  429. texture_cache.FlushRegion(addr, size);
  430. buffer_cache.FlushRegion(cache_addr, size);
  431. query_cache.FlushRegion(cache_addr, size);
  432. }
  433. void RasterizerVulkan::InvalidateRegion(VAddr addr, u64 size) {
  434. if (!addr || !size) {
  435. return;
  436. }
  437. CacheAddr cache_addr = ToCacheAddr(system.Memory().GetPointer(addr));
  438. texture_cache.InvalidateRegion(addr, size);
  439. pipeline_cache.InvalidateRegion(cache_addr, size);
  440. buffer_cache.InvalidateRegion(cache_addr, size);
  441. query_cache.InvalidateRegion(cache_addr, size);
  442. }
  443. void RasterizerVulkan::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  444. FlushRegion(addr, size);
  445. InvalidateRegion(addr, size);
  446. }
  447. void RasterizerVulkan::FlushCommands() {
  448. if (draw_counter > 0) {
  449. draw_counter = 0;
  450. scheduler.Flush();
  451. }
  452. }
  453. void RasterizerVulkan::TickFrame() {
  454. draw_counter = 0;
  455. update_descriptor_queue.TickFrame();
  456. buffer_cache.TickFrame();
  457. staging_pool.TickFrame();
  458. }
  459. bool RasterizerVulkan::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  460. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  461. const Tegra::Engines::Fermi2D::Config& copy_config) {
  462. texture_cache.DoFermiCopy(src, dst, copy_config);
  463. return true;
  464. }
  465. bool RasterizerVulkan::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  466. VAddr framebuffer_addr, u32 pixel_stride) {
  467. if (!framebuffer_addr) {
  468. return false;
  469. }
  470. const auto surface{texture_cache.TryFindFramebufferSurface(framebuffer_addr)};
  471. if (!surface) {
  472. return false;
  473. }
  474. // Verify that the cached surface is the same size and format as the requested framebuffer
  475. const auto& params{surface->GetSurfaceParams()};
  476. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  477. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  478. screen_info.image = &surface->GetImage();
  479. screen_info.width = params.width;
  480. screen_info.height = params.height;
  481. screen_info.is_srgb = surface->GetSurfaceParams().srgb_conversion;
  482. return true;
  483. }
  484. void RasterizerVulkan::SetupDirtyFlags() {
  485. state_tracker.Initialize();
  486. }
  487. void RasterizerVulkan::FlushWork() {
  488. static constexpr u32 DRAWS_TO_DISPATCH = 4096;
  489. // Only check multiples of 8 draws
  490. static_assert(DRAWS_TO_DISPATCH % 8 == 0);
  491. if ((++draw_counter & 7) != 7) {
  492. return;
  493. }
  494. if (draw_counter < DRAWS_TO_DISPATCH) {
  495. // Send recorded tasks to the worker thread
  496. scheduler.DispatchWork();
  497. return;
  498. }
  499. // Otherwise (every certain number of draws) flush execution.
  500. // This submits commands to the Vulkan driver.
  501. scheduler.Flush();
  502. draw_counter = 0;
  503. }
  504. RasterizerVulkan::Texceptions RasterizerVulkan::UpdateAttachments() {
  505. MICROPROFILE_SCOPE(Vulkan_RenderTargets);
  506. auto& dirty = system.GPU().Maxwell3D().dirty.flags;
  507. const bool update_rendertargets = dirty[VideoCommon::Dirty::RenderTargets];
  508. dirty[VideoCommon::Dirty::RenderTargets] = false;
  509. texture_cache.GuardRenderTargets(true);
  510. Texceptions texceptions;
  511. for (std::size_t rt = 0; rt < Maxwell::NumRenderTargets; ++rt) {
  512. if (update_rendertargets) {
  513. color_attachments[rt] = texture_cache.GetColorBufferSurface(rt, true);
  514. }
  515. if (color_attachments[rt] && WalkAttachmentOverlaps(*color_attachments[rt])) {
  516. texceptions[rt] = true;
  517. }
  518. }
  519. if (update_rendertargets) {
  520. zeta_attachment = texture_cache.GetDepthBufferSurface(true);
  521. }
  522. if (zeta_attachment && WalkAttachmentOverlaps(*zeta_attachment)) {
  523. texceptions[ZETA_TEXCEPTION_INDEX] = true;
  524. }
  525. texture_cache.GuardRenderTargets(false);
  526. return texceptions;
  527. }
  528. bool RasterizerVulkan::WalkAttachmentOverlaps(const CachedSurfaceView& attachment) {
  529. bool overlap = false;
  530. for (auto& [view, layout] : sampled_views) {
  531. if (!attachment.IsSameSurface(*view)) {
  532. continue;
  533. }
  534. overlap = true;
  535. *layout = vk::ImageLayout::eGeneral;
  536. }
  537. return overlap;
  538. }
  539. std::tuple<vk::Framebuffer, vk::Extent2D> RasterizerVulkan::ConfigureFramebuffers(
  540. vk::RenderPass renderpass) {
  541. FramebufferCacheKey key{renderpass, std::numeric_limits<u32>::max(),
  542. std::numeric_limits<u32>::max(), std::numeric_limits<u32>::max()};
  543. const auto try_push = [&](const View& view) {
  544. if (!view) {
  545. return false;
  546. }
  547. key.views.push_back(view->GetHandle());
  548. key.width = std::min(key.width, view->GetWidth());
  549. key.height = std::min(key.height, view->GetHeight());
  550. key.layers = std::min(key.layers, view->GetNumLayers());
  551. return true;
  552. };
  553. for (std::size_t index = 0; index < std::size(color_attachments); ++index) {
  554. if (try_push(color_attachments[index])) {
  555. texture_cache.MarkColorBufferInUse(index);
  556. }
  557. }
  558. if (try_push(zeta_attachment)) {
  559. texture_cache.MarkDepthBufferInUse();
  560. }
  561. const auto [fbentry, is_cache_miss] = framebuffer_cache.try_emplace(key);
  562. auto& framebuffer = fbentry->second;
  563. if (is_cache_miss) {
  564. const vk::FramebufferCreateInfo framebuffer_ci(
  565. {}, key.renderpass, static_cast<u32>(key.views.size()), key.views.data(), key.width,
  566. key.height, key.layers);
  567. const auto dev = device.GetLogical();
  568. const auto& dld = device.GetDispatchLoader();
  569. framebuffer = dev.createFramebufferUnique(framebuffer_ci, nullptr, dld);
  570. }
  571. return {*framebuffer, vk::Extent2D{key.width, key.height}};
  572. }
  573. RasterizerVulkan::DrawParameters RasterizerVulkan::SetupGeometry(FixedPipelineState& fixed_state,
  574. BufferBindings& buffer_bindings,
  575. bool is_indexed,
  576. bool is_instanced) {
  577. MICROPROFILE_SCOPE(Vulkan_Geometry);
  578. const auto& gpu = system.GPU().Maxwell3D();
  579. const auto& regs = gpu.regs;
  580. SetupVertexArrays(fixed_state.vertex_input, buffer_bindings);
  581. const u32 base_instance = regs.vb_base_instance;
  582. const u32 num_instances = is_instanced ? gpu.mme_draw.instance_count : 1;
  583. const u32 base_vertex = is_indexed ? regs.vb_element_base : regs.vertex_buffer.first;
  584. const u32 num_vertices = is_indexed ? regs.index_array.count : regs.vertex_buffer.count;
  585. DrawParameters params{base_instance, num_instances, base_vertex, num_vertices, is_indexed};
  586. SetupIndexBuffer(buffer_bindings, params, is_indexed);
  587. return params;
  588. }
  589. void RasterizerVulkan::SetupShaderDescriptors(
  590. const std::array<Shader, Maxwell::MaxShaderProgram>& shaders) {
  591. texture_cache.GuardSamplers(true);
  592. for (std::size_t stage = 0; stage < Maxwell::MaxShaderStage; ++stage) {
  593. // Skip VertexA stage
  594. const auto& shader = shaders[stage + 1];
  595. if (!shader) {
  596. continue;
  597. }
  598. const auto& entries = shader->GetEntries();
  599. SetupGraphicsConstBuffers(entries, stage);
  600. SetupGraphicsGlobalBuffers(entries, stage);
  601. SetupGraphicsTexelBuffers(entries, stage);
  602. SetupGraphicsTextures(entries, stage);
  603. SetupGraphicsImages(entries, stage);
  604. }
  605. texture_cache.GuardSamplers(false);
  606. }
  607. void RasterizerVulkan::SetupImageTransitions(
  608. Texceptions texceptions, const std::array<View, Maxwell::NumRenderTargets>& color_attachments,
  609. const View& zeta_attachment) {
  610. TransitionImages(sampled_views, vk::PipelineStageFlagBits::eAllGraphics,
  611. vk::AccessFlagBits::eShaderRead);
  612. TransitionImages(image_views, vk::PipelineStageFlagBits::eAllGraphics,
  613. vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite);
  614. for (std::size_t rt = 0; rt < std::size(color_attachments); ++rt) {
  615. const auto color_attachment = color_attachments[rt];
  616. if (color_attachment == nullptr) {
  617. continue;
  618. }
  619. const auto image_layout =
  620. texceptions[rt] ? vk::ImageLayout::eGeneral : vk::ImageLayout::eColorAttachmentOptimal;
  621. color_attachment->Transition(
  622. image_layout, vk::PipelineStageFlagBits::eColorAttachmentOutput,
  623. vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite);
  624. }
  625. if (zeta_attachment != nullptr) {
  626. const auto image_layout = texceptions[ZETA_TEXCEPTION_INDEX]
  627. ? vk::ImageLayout::eGeneral
  628. : vk::ImageLayout::eDepthStencilAttachmentOptimal;
  629. zeta_attachment->Transition(image_layout, vk::PipelineStageFlagBits::eLateFragmentTests,
  630. vk::AccessFlagBits::eDepthStencilAttachmentRead |
  631. vk::AccessFlagBits::eDepthStencilAttachmentWrite);
  632. }
  633. }
  634. void RasterizerVulkan::UpdateDynamicStates() {
  635. auto& regs = system.GPU().Maxwell3D().regs;
  636. UpdateViewportsState(regs);
  637. UpdateScissorsState(regs);
  638. UpdateDepthBias(regs);
  639. UpdateBlendConstants(regs);
  640. UpdateDepthBounds(regs);
  641. UpdateStencilFaces(regs);
  642. }
  643. void RasterizerVulkan::BeginTransformFeedback() {
  644. const auto& regs = system.GPU().Maxwell3D().regs;
  645. if (regs.tfb_enabled == 0) {
  646. return;
  647. }
  648. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationControl) ||
  649. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationEval) ||
  650. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::Geometry));
  651. UNIMPLEMENTED_IF(regs.tfb_bindings[1].buffer_enable);
  652. UNIMPLEMENTED_IF(regs.tfb_bindings[2].buffer_enable);
  653. UNIMPLEMENTED_IF(regs.tfb_bindings[3].buffer_enable);
  654. const auto& binding = regs.tfb_bindings[0];
  655. UNIMPLEMENTED_IF(binding.buffer_enable == 0);
  656. UNIMPLEMENTED_IF(binding.buffer_offset != 0);
  657. const GPUVAddr gpu_addr = binding.Address();
  658. const std::size_t size = binding.buffer_size;
  659. const auto [buffer, offset] = buffer_cache.UploadMemory(gpu_addr, size, 4, true);
  660. scheduler.Record([buffer = *buffer, offset = offset, size](auto cmdbuf, auto& dld) {
  661. cmdbuf.bindTransformFeedbackBuffersEXT(0, {buffer}, {offset}, {size}, dld);
  662. cmdbuf.beginTransformFeedbackEXT(0, {}, {}, dld);
  663. });
  664. }
  665. void RasterizerVulkan::EndTransformFeedback() {
  666. const auto& regs = system.GPU().Maxwell3D().regs;
  667. if (regs.tfb_enabled == 0) {
  668. return;
  669. }
  670. scheduler.Record(
  671. [](auto cmdbuf, auto& dld) { cmdbuf.endTransformFeedbackEXT(0, {}, {}, dld); });
  672. }
  673. void RasterizerVulkan::SetupVertexArrays(FixedPipelineState::VertexInput& vertex_input,
  674. BufferBindings& buffer_bindings) {
  675. const auto& regs = system.GPU().Maxwell3D().regs;
  676. for (u32 index = 0; index < static_cast<u32>(Maxwell::NumVertexAttributes); ++index) {
  677. const auto& attrib = regs.vertex_attrib_format[index];
  678. if (!attrib.IsValid()) {
  679. continue;
  680. }
  681. const auto& buffer = regs.vertex_array[attrib.buffer];
  682. ASSERT(buffer.IsEnabled());
  683. vertex_input.attributes[vertex_input.num_attributes++] =
  684. FixedPipelineState::VertexAttribute(index, attrib.buffer, attrib.type, attrib.size,
  685. attrib.offset);
  686. }
  687. for (u32 index = 0; index < static_cast<u32>(Maxwell::NumVertexArrays); ++index) {
  688. const auto& vertex_array = regs.vertex_array[index];
  689. if (!vertex_array.IsEnabled()) {
  690. continue;
  691. }
  692. const GPUVAddr start{vertex_array.StartAddress()};
  693. const GPUVAddr end{regs.vertex_array_limit[index].LimitAddress()};
  694. ASSERT(end > start);
  695. const std::size_t size{end - start + 1};
  696. const auto [buffer, offset] = buffer_cache.UploadMemory(start, size);
  697. vertex_input.bindings[vertex_input.num_bindings++] = FixedPipelineState::VertexBinding(
  698. index, vertex_array.stride,
  699. regs.instanced_arrays.IsInstancingEnabled(index) ? vertex_array.divisor : 0);
  700. buffer_bindings.AddVertexBinding(buffer, offset);
  701. }
  702. }
  703. void RasterizerVulkan::SetupIndexBuffer(BufferBindings& buffer_bindings, DrawParameters& params,
  704. bool is_indexed) {
  705. const auto& regs = system.GPU().Maxwell3D().regs;
  706. switch (regs.draw.topology) {
  707. case Maxwell::PrimitiveTopology::Quads:
  708. if (params.is_indexed) {
  709. UNIMPLEMENTED();
  710. } else {
  711. const auto [buffer, offset] =
  712. quad_array_pass.Assemble(params.num_vertices, params.base_vertex);
  713. buffer_bindings.SetIndexBinding(&buffer, offset, vk::IndexType::eUint32);
  714. params.base_vertex = 0;
  715. params.num_vertices = params.num_vertices * 6 / 4;
  716. params.is_indexed = true;
  717. }
  718. break;
  719. default: {
  720. if (!is_indexed) {
  721. break;
  722. }
  723. const GPUVAddr gpu_addr = regs.index_array.IndexStart();
  724. auto [buffer, offset] = buffer_cache.UploadMemory(gpu_addr, CalculateIndexBufferSize());
  725. auto format = regs.index_array.format;
  726. const bool is_uint8 = format == Maxwell::IndexFormat::UnsignedByte;
  727. if (is_uint8 && !device.IsExtIndexTypeUint8Supported()) {
  728. std::tie(buffer, offset) = uint8_pass.Assemble(params.num_vertices, *buffer, offset);
  729. format = Maxwell::IndexFormat::UnsignedShort;
  730. }
  731. buffer_bindings.SetIndexBinding(buffer, offset, MaxwellToVK::IndexFormat(device, format));
  732. break;
  733. }
  734. }
  735. }
  736. void RasterizerVulkan::SetupGraphicsConstBuffers(const ShaderEntries& entries, std::size_t stage) {
  737. MICROPROFILE_SCOPE(Vulkan_ConstBuffers);
  738. const auto& gpu = system.GPU().Maxwell3D();
  739. const auto& shader_stage = gpu.state.shader_stages[stage];
  740. for (const auto& entry : entries.const_buffers) {
  741. SetupConstBuffer(entry, shader_stage.const_buffers[entry.GetIndex()]);
  742. }
  743. }
  744. void RasterizerVulkan::SetupGraphicsGlobalBuffers(const ShaderEntries& entries, std::size_t stage) {
  745. MICROPROFILE_SCOPE(Vulkan_GlobalBuffers);
  746. auto& gpu{system.GPU()};
  747. const auto cbufs{gpu.Maxwell3D().state.shader_stages[stage]};
  748. for (const auto& entry : entries.global_buffers) {
  749. const auto addr = cbufs.const_buffers[entry.GetCbufIndex()].address + entry.GetCbufOffset();
  750. SetupGlobalBuffer(entry, addr);
  751. }
  752. }
  753. void RasterizerVulkan::SetupGraphicsTexelBuffers(const ShaderEntries& entries, std::size_t stage) {
  754. MICROPROFILE_SCOPE(Vulkan_Textures);
  755. const auto& gpu = system.GPU().Maxwell3D();
  756. for (const auto& entry : entries.texel_buffers) {
  757. const auto image = GetTextureInfo(gpu, entry, stage).tic;
  758. SetupTexelBuffer(image, entry);
  759. }
  760. }
  761. void RasterizerVulkan::SetupGraphicsTextures(const ShaderEntries& entries, std::size_t stage) {
  762. MICROPROFILE_SCOPE(Vulkan_Textures);
  763. const auto& gpu = system.GPU().Maxwell3D();
  764. for (const auto& entry : entries.samplers) {
  765. for (std::size_t i = 0; i < entry.Size(); ++i) {
  766. const auto texture = GetTextureInfo(gpu, entry, stage, i);
  767. SetupTexture(texture, entry);
  768. }
  769. }
  770. }
  771. void RasterizerVulkan::SetupGraphicsImages(const ShaderEntries& entries, std::size_t stage) {
  772. MICROPROFILE_SCOPE(Vulkan_Images);
  773. const auto& gpu = system.GPU().Maxwell3D();
  774. for (const auto& entry : entries.images) {
  775. const auto tic = GetTextureInfo(gpu, entry, stage).tic;
  776. SetupImage(tic, entry);
  777. }
  778. }
  779. void RasterizerVulkan::SetupComputeConstBuffers(const ShaderEntries& entries) {
  780. MICROPROFILE_SCOPE(Vulkan_ConstBuffers);
  781. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  782. for (const auto& entry : entries.const_buffers) {
  783. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  784. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  785. Tegra::Engines::ConstBufferInfo buffer;
  786. buffer.address = config.Address();
  787. buffer.size = config.size;
  788. buffer.enabled = mask[entry.GetIndex()];
  789. SetupConstBuffer(entry, buffer);
  790. }
  791. }
  792. void RasterizerVulkan::SetupComputeGlobalBuffers(const ShaderEntries& entries) {
  793. MICROPROFILE_SCOPE(Vulkan_GlobalBuffers);
  794. const auto cbufs{system.GPU().KeplerCompute().launch_description.const_buffer_config};
  795. for (const auto& entry : entries.global_buffers) {
  796. const auto addr{cbufs[entry.GetCbufIndex()].Address() + entry.GetCbufOffset()};
  797. SetupGlobalBuffer(entry, addr);
  798. }
  799. }
  800. void RasterizerVulkan::SetupComputeTexelBuffers(const ShaderEntries& entries) {
  801. MICROPROFILE_SCOPE(Vulkan_Textures);
  802. const auto& gpu = system.GPU().KeplerCompute();
  803. for (const auto& entry : entries.texel_buffers) {
  804. const auto image = GetTextureInfo(gpu, entry, ComputeShaderIndex).tic;
  805. SetupTexelBuffer(image, entry);
  806. }
  807. }
  808. void RasterizerVulkan::SetupComputeTextures(const ShaderEntries& entries) {
  809. MICROPROFILE_SCOPE(Vulkan_Textures);
  810. const auto& gpu = system.GPU().KeplerCompute();
  811. for (const auto& entry : entries.samplers) {
  812. for (std::size_t i = 0; i < entry.Size(); ++i) {
  813. const auto texture = GetTextureInfo(gpu, entry, ComputeShaderIndex, i);
  814. SetupTexture(texture, entry);
  815. }
  816. }
  817. }
  818. void RasterizerVulkan::SetupComputeImages(const ShaderEntries& entries) {
  819. MICROPROFILE_SCOPE(Vulkan_Images);
  820. const auto& gpu = system.GPU().KeplerCompute();
  821. for (const auto& entry : entries.images) {
  822. const auto tic = GetTextureInfo(gpu, entry, ComputeShaderIndex).tic;
  823. SetupImage(tic, entry);
  824. }
  825. }
  826. void RasterizerVulkan::SetupConstBuffer(const ConstBufferEntry& entry,
  827. const Tegra::Engines::ConstBufferInfo& buffer) {
  828. if (!buffer.enabled) {
  829. // Set values to zero to unbind buffers
  830. update_descriptor_queue.AddBuffer(buffer_cache.GetEmptyBuffer(sizeof(float)), 0,
  831. sizeof(float));
  832. return;
  833. }
  834. // Align the size to avoid bad std140 interactions
  835. const std::size_t size =
  836. Common::AlignUp(CalculateConstBufferSize(entry, buffer), 4 * sizeof(float));
  837. ASSERT(size <= MaxConstbufferSize);
  838. const auto [buffer_handle, offset] =
  839. buffer_cache.UploadMemory(buffer.address, size, device.GetUniformBufferAlignment());
  840. update_descriptor_queue.AddBuffer(buffer_handle, offset, size);
  841. }
  842. void RasterizerVulkan::SetupGlobalBuffer(const GlobalBufferEntry& entry, GPUVAddr address) {
  843. auto& memory_manager{system.GPU().MemoryManager()};
  844. const auto actual_addr = memory_manager.Read<u64>(address);
  845. const auto size = memory_manager.Read<u32>(address + 8);
  846. if (size == 0) {
  847. // Sometimes global memory pointers don't have a proper size. Upload a dummy entry because
  848. // Vulkan doesn't like empty buffers.
  849. constexpr std::size_t dummy_size = 4;
  850. const auto buffer = buffer_cache.GetEmptyBuffer(dummy_size);
  851. update_descriptor_queue.AddBuffer(buffer, 0, dummy_size);
  852. return;
  853. }
  854. const auto [buffer, offset] = buffer_cache.UploadMemory(
  855. actual_addr, size, device.GetStorageBufferAlignment(), entry.IsWritten());
  856. update_descriptor_queue.AddBuffer(buffer, offset, size);
  857. }
  858. void RasterizerVulkan::SetupTexelBuffer(const Tegra::Texture::TICEntry& tic,
  859. const TexelBufferEntry& entry) {
  860. const auto view = texture_cache.GetTextureSurface(tic, entry);
  861. ASSERT(view->IsBufferView());
  862. update_descriptor_queue.AddTexelBuffer(view->GetBufferView());
  863. }
  864. void RasterizerVulkan::SetupTexture(const Tegra::Texture::FullTextureInfo& texture,
  865. const SamplerEntry& entry) {
  866. auto view = texture_cache.GetTextureSurface(texture.tic, entry);
  867. ASSERT(!view->IsBufferView());
  868. const auto image_view = view->GetHandle(texture.tic.x_source, texture.tic.y_source,
  869. texture.tic.z_source, texture.tic.w_source);
  870. const auto sampler = sampler_cache.GetSampler(texture.tsc);
  871. update_descriptor_queue.AddSampledImage(sampler, image_view);
  872. const auto image_layout = update_descriptor_queue.GetLastImageLayout();
  873. *image_layout = vk::ImageLayout::eShaderReadOnlyOptimal;
  874. sampled_views.push_back(ImageView{std::move(view), image_layout});
  875. }
  876. void RasterizerVulkan::SetupImage(const Tegra::Texture::TICEntry& tic, const ImageEntry& entry) {
  877. auto view = texture_cache.GetImageSurface(tic, entry);
  878. if (entry.IsWritten()) {
  879. view->MarkAsModified(texture_cache.Tick());
  880. }
  881. UNIMPLEMENTED_IF(tic.IsBuffer());
  882. const auto image_view = view->GetHandle(tic.x_source, tic.y_source, tic.z_source, tic.w_source);
  883. update_descriptor_queue.AddImage(image_view);
  884. const auto image_layout = update_descriptor_queue.GetLastImageLayout();
  885. *image_layout = vk::ImageLayout::eGeneral;
  886. image_views.push_back(ImageView{std::move(view), image_layout});
  887. }
  888. void RasterizerVulkan::UpdateViewportsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  889. if (!state_tracker.TouchViewports()) {
  890. return;
  891. }
  892. const std::array viewports{
  893. GetViewportState(device, regs, 0), GetViewportState(device, regs, 1),
  894. GetViewportState(device, regs, 2), GetViewportState(device, regs, 3),
  895. GetViewportState(device, regs, 4), GetViewportState(device, regs, 5),
  896. GetViewportState(device, regs, 6), GetViewportState(device, regs, 7),
  897. GetViewportState(device, regs, 8), GetViewportState(device, regs, 9),
  898. GetViewportState(device, regs, 10), GetViewportState(device, regs, 11),
  899. GetViewportState(device, regs, 12), GetViewportState(device, regs, 13),
  900. GetViewportState(device, regs, 14), GetViewportState(device, regs, 15)};
  901. scheduler.Record([viewports](auto cmdbuf, auto& dld) {
  902. cmdbuf.setViewport(0, static_cast<u32>(viewports.size()), viewports.data(), dld);
  903. });
  904. }
  905. void RasterizerVulkan::UpdateScissorsState(Tegra::Engines::Maxwell3D::Regs& regs) {
  906. if (!state_tracker.TouchScissors()) {
  907. return;
  908. }
  909. const std::array scissors = {
  910. GetScissorState(regs, 0), GetScissorState(regs, 1), GetScissorState(regs, 2),
  911. GetScissorState(regs, 3), GetScissorState(regs, 4), GetScissorState(regs, 5),
  912. GetScissorState(regs, 6), GetScissorState(regs, 7), GetScissorState(regs, 8),
  913. GetScissorState(regs, 9), GetScissorState(regs, 10), GetScissorState(regs, 11),
  914. GetScissorState(regs, 12), GetScissorState(regs, 13), GetScissorState(regs, 14),
  915. GetScissorState(regs, 15)};
  916. scheduler.Record([scissors](auto cmdbuf, auto& dld) {
  917. cmdbuf.setScissor(0, static_cast<u32>(scissors.size()), scissors.data(), dld);
  918. });
  919. }
  920. void RasterizerVulkan::UpdateDepthBias(Tegra::Engines::Maxwell3D::Regs& regs) {
  921. if (!state_tracker.TouchDepthBias()) {
  922. return;
  923. }
  924. scheduler.Record([constant = regs.polygon_offset_units, clamp = regs.polygon_offset_clamp,
  925. factor = regs.polygon_offset_factor](auto cmdbuf, auto& dld) {
  926. cmdbuf.setDepthBias(constant, clamp, factor / 2.0f, dld);
  927. });
  928. }
  929. void RasterizerVulkan::UpdateBlendConstants(Tegra::Engines::Maxwell3D::Regs& regs) {
  930. if (!state_tracker.TouchBlendConstants()) {
  931. return;
  932. }
  933. const std::array blend_color = {regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  934. regs.blend_color.a};
  935. scheduler.Record([blend_color](auto cmdbuf, auto& dld) {
  936. cmdbuf.setBlendConstants(blend_color.data(), dld);
  937. });
  938. }
  939. void RasterizerVulkan::UpdateDepthBounds(Tegra::Engines::Maxwell3D::Regs& regs) {
  940. if (!state_tracker.TouchDepthBounds()) {
  941. return;
  942. }
  943. scheduler.Record([min = regs.depth_bounds[0], max = regs.depth_bounds[1]](
  944. auto cmdbuf, auto& dld) { cmdbuf.setDepthBounds(min, max, dld); });
  945. }
  946. void RasterizerVulkan::UpdateStencilFaces(Tegra::Engines::Maxwell3D::Regs& regs) {
  947. if (!state_tracker.TouchStencilProperties()) {
  948. return;
  949. }
  950. if (regs.stencil_two_side_enable) {
  951. // Separate values per face
  952. scheduler.Record(
  953. [front_ref = regs.stencil_front_func_ref, front_write_mask = regs.stencil_front_mask,
  954. front_test_mask = regs.stencil_front_func_mask, back_ref = regs.stencil_back_func_ref,
  955. back_write_mask = regs.stencil_back_mask,
  956. back_test_mask = regs.stencil_back_func_mask](auto cmdbuf, auto& dld) {
  957. // Front face
  958. cmdbuf.setStencilReference(vk::StencilFaceFlagBits::eFront, front_ref, dld);
  959. cmdbuf.setStencilWriteMask(vk::StencilFaceFlagBits::eFront, front_write_mask, dld);
  960. cmdbuf.setStencilCompareMask(vk::StencilFaceFlagBits::eFront, front_test_mask, dld);
  961. // Back face
  962. cmdbuf.setStencilReference(vk::StencilFaceFlagBits::eBack, back_ref, dld);
  963. cmdbuf.setStencilWriteMask(vk::StencilFaceFlagBits::eBack, back_write_mask, dld);
  964. cmdbuf.setStencilCompareMask(vk::StencilFaceFlagBits::eBack, back_test_mask, dld);
  965. });
  966. } else {
  967. // Front face defines both faces
  968. scheduler.Record([ref = regs.stencil_back_func_ref, write_mask = regs.stencil_back_mask,
  969. test_mask = regs.stencil_back_func_mask](auto cmdbuf, auto& dld) {
  970. cmdbuf.setStencilReference(vk::StencilFaceFlagBits::eFrontAndBack, ref, dld);
  971. cmdbuf.setStencilWriteMask(vk::StencilFaceFlagBits::eFrontAndBack, write_mask, dld);
  972. cmdbuf.setStencilCompareMask(vk::StencilFaceFlagBits::eFrontAndBack, test_mask, dld);
  973. });
  974. }
  975. }
  976. std::size_t RasterizerVulkan::CalculateGraphicsStreamBufferSize(bool is_indexed) const {
  977. std::size_t size = CalculateVertexArraysSize();
  978. if (is_indexed) {
  979. size = Common::AlignUp(size, 4) + CalculateIndexBufferSize();
  980. }
  981. size += Maxwell::MaxConstBuffers * (MaxConstbufferSize + device.GetUniformBufferAlignment());
  982. return size;
  983. }
  984. std::size_t RasterizerVulkan::CalculateComputeStreamBufferSize() const {
  985. return Tegra::Engines::KeplerCompute::NumConstBuffers *
  986. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  987. }
  988. std::size_t RasterizerVulkan::CalculateVertexArraysSize() const {
  989. const auto& regs = system.GPU().Maxwell3D().regs;
  990. std::size_t size = 0;
  991. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  992. // This implementation assumes that all attributes are used in the shader.
  993. const GPUVAddr start{regs.vertex_array[index].StartAddress()};
  994. const GPUVAddr end{regs.vertex_array_limit[index].LimitAddress()};
  995. DEBUG_ASSERT(end >= start);
  996. size += (end - start + 1) * regs.vertex_array[index].enable;
  997. }
  998. return size;
  999. }
  1000. std::size_t RasterizerVulkan::CalculateIndexBufferSize() const {
  1001. const auto& regs = system.GPU().Maxwell3D().regs;
  1002. return static_cast<std::size_t>(regs.index_array.count) *
  1003. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  1004. }
  1005. std::size_t RasterizerVulkan::CalculateConstBufferSize(
  1006. const ConstBufferEntry& entry, const Tegra::Engines::ConstBufferInfo& buffer) const {
  1007. if (entry.IsIndirect()) {
  1008. // Buffer is accessed indirectly, so upload the entire thing
  1009. return buffer.size;
  1010. } else {
  1011. // Buffer is accessed directly, upload just what we use
  1012. return entry.GetSize();
  1013. }
  1014. }
  1015. RenderPassParams RasterizerVulkan::GetRenderPassParams(Texceptions texceptions) const {
  1016. using namespace VideoCore::Surface;
  1017. const auto& regs = system.GPU().Maxwell3D().regs;
  1018. RenderPassParams renderpass_params;
  1019. for (std::size_t rt = 0; rt < static_cast<std::size_t>(regs.rt_control.count); ++rt) {
  1020. const auto& rendertarget = regs.rt[rt];
  1021. if (rendertarget.Address() == 0 || rendertarget.format == Tegra::RenderTargetFormat::NONE) {
  1022. continue;
  1023. }
  1024. renderpass_params.color_attachments.push_back(RenderPassParams::ColorAttachment{
  1025. static_cast<u32>(rt), PixelFormatFromRenderTargetFormat(rendertarget.format),
  1026. texceptions[rt]});
  1027. }
  1028. renderpass_params.has_zeta = regs.zeta_enable;
  1029. if (renderpass_params.has_zeta) {
  1030. renderpass_params.zeta_pixel_format = PixelFormatFromDepthFormat(regs.zeta.format);
  1031. renderpass_params.zeta_texception = texceptions[ZETA_TEXCEPTION_INDEX];
  1032. }
  1033. return renderpass_params;
  1034. }
  1035. } // namespace Vulkan