vk_rasterizer.cpp 62 KB

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