gl_rasterizer.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. // Copyright 2015 Citra 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 <string>
  8. #include <string_view>
  9. #include <tuple>
  10. #include <utility>
  11. #include <glad/glad.h>
  12. #include "common/alignment.h"
  13. #include "common/assert.h"
  14. #include "common/logging/log.h"
  15. #include "common/math_util.h"
  16. #include "common/microprofile.h"
  17. #include "common/scope_exit.h"
  18. #include "core/core.h"
  19. #include "core/frontend/emu_window.h"
  20. #include "core/hle/kernel/process.h"
  21. #include "core/settings.h"
  22. #include "video_core/engines/maxwell_3d.h"
  23. #include "video_core/renderer_opengl/gl_rasterizer.h"
  24. #include "video_core/renderer_opengl/gl_shader_cache.h"
  25. #include "video_core/renderer_opengl/gl_shader_gen.h"
  26. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  27. #include "video_core/renderer_opengl/renderer_opengl.h"
  28. #include "video_core/video_core.h"
  29. namespace OpenGL {
  30. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  31. using PixelFormat = VideoCore::Surface::PixelFormat;
  32. using SurfaceType = VideoCore::Surface::SurfaceType;
  33. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Format Setup", MP_RGB(128, 128, 192));
  34. MICROPROFILE_DEFINE(OpenGL_VB, "OpenGL", "Vertex Buffer Setup", MP_RGB(128, 128, 192));
  35. MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192));
  36. MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192));
  37. MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192));
  38. MICROPROFILE_DEFINE(OpenGL_Texture, "OpenGL", "Texture Setup", MP_RGB(128, 128, 192));
  39. MICROPROFILE_DEFINE(OpenGL_Framebuffer, "OpenGL", "Framebuffer Setup", MP_RGB(128, 128, 192));
  40. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  41. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
  42. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
  43. MICROPROFILE_DEFINE(OpenGL_PrimitiveAssembly, "OpenGL", "Prim Asmbl", MP_RGB(255, 100, 100));
  44. struct DrawParameters {
  45. GLenum primitive_mode;
  46. GLsizei count;
  47. GLint current_instance;
  48. bool use_indexed;
  49. GLint vertex_first;
  50. GLenum index_format;
  51. GLint base_vertex;
  52. GLintptr index_buffer_offset;
  53. void DispatchDraw() const {
  54. if (use_indexed) {
  55. const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
  56. if (current_instance > 0) {
  57. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
  58. index_buffer_ptr, 1, base_vertex,
  59. current_instance);
  60. } else {
  61. glDrawElementsBaseVertex(primitive_mode, count, index_format, index_buffer_ptr,
  62. base_vertex);
  63. }
  64. } else {
  65. if (current_instance > 0) {
  66. glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, 1,
  67. current_instance);
  68. } else {
  69. glDrawArrays(primitive_mode, vertex_first, count);
  70. }
  71. }
  72. }
  73. };
  74. struct FramebufferCacheKey {
  75. bool is_single_buffer = false;
  76. bool stencil_enable = false;
  77. std::array<GLenum, Maxwell::NumRenderTargets> color_attachments{};
  78. std::array<GLuint, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets> colors{};
  79. u32 colors_count = 0;
  80. GLuint zeta = 0;
  81. auto Tie() const {
  82. return std::tie(is_single_buffer, stencil_enable, color_attachments, colors, colors_count,
  83. zeta);
  84. }
  85. bool operator<(const FramebufferCacheKey& rhs) const {
  86. return Tie() < rhs.Tie();
  87. }
  88. };
  89. RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, Core::System& system,
  90. ScreenInfo& info)
  91. : res_cache{*this}, shader_cache{*this, system}, global_cache{*this}, emu_window{window},
  92. screen_info{info}, buffer_cache(*this, STREAM_BUFFER_SIZE) {
  93. // Create sampler objects
  94. for (std::size_t i = 0; i < texture_samplers.size(); ++i) {
  95. texture_samplers[i].Create();
  96. state.texture_units[i].sampler = texture_samplers[i].sampler.handle;
  97. }
  98. OpenGLState::ApplyDefaultState();
  99. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  100. state.draw.shader_program = 0;
  101. state.Apply();
  102. glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uniform_buffer_alignment);
  103. LOG_CRITICAL(Render_OpenGL, "Sync fixed function OpenGL state here!");
  104. CheckExtensions();
  105. }
  106. RasterizerOpenGL::~RasterizerOpenGL() {}
  107. void RasterizerOpenGL::CheckExtensions() {
  108. if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
  109. LOG_WARNING(
  110. Render_OpenGL,
  111. "Anisotropic filter is not supported! This can cause graphical issues in some games.");
  112. }
  113. if (!GLAD_GL_ARB_buffer_storage) {
  114. LOG_WARNING(
  115. Render_OpenGL,
  116. "Buffer storage control is not supported! This can cause performance degradation.");
  117. }
  118. }
  119. GLuint RasterizerOpenGL::SetupVertexFormat() {
  120. auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  121. const auto& regs = gpu.regs;
  122. if (!gpu.dirty_flags.vertex_attrib_format) {
  123. return state.draw.vertex_array;
  124. }
  125. gpu.dirty_flags.vertex_attrib_format = false;
  126. MICROPROFILE_SCOPE(OpenGL_VAO);
  127. auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
  128. auto& vao_entry = iter->second;
  129. if (is_cache_miss) {
  130. vao_entry.Create();
  131. const GLuint vao = vao_entry.handle;
  132. // Eventhough we are using DSA to create this vertex array, there is a bug on Intel's blob
  133. // that fails to properly create the vertex array if it's not bound even after creating it
  134. // with glCreateVertexArrays
  135. state.draw.vertex_array = vao;
  136. state.ApplyVertexArrayState();
  137. glVertexArrayElementBuffer(vao, buffer_cache.GetHandle());
  138. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  139. // Enables the first 16 vertex attributes always, as we don't know which ones are actually
  140. // used until shader time. Note, Tegra technically supports 32, but we're capping this to 16
  141. // for now to avoid OpenGL errors.
  142. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  143. // assume every shader uses them all.
  144. for (u32 index = 0; index < 16; ++index) {
  145. const auto& attrib = regs.vertex_attrib_format[index];
  146. // Ignore invalid attributes.
  147. if (!attrib.IsValid())
  148. continue;
  149. const auto& buffer = regs.vertex_array[attrib.buffer];
  150. LOG_TRACE(HW_GPU,
  151. "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  152. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  153. attrib.offset.Value(), attrib.IsNormalized());
  154. ASSERT(buffer.IsEnabled());
  155. glEnableVertexArrayAttrib(vao, index);
  156. if (attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::SignedInt ||
  157. attrib.type ==
  158. Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::UnsignedInt) {
  159. glVertexArrayAttribIFormat(vao, index, attrib.ComponentCount(),
  160. MaxwellToGL::VertexType(attrib), attrib.offset);
  161. } else {
  162. glVertexArrayAttribFormat(
  163. vao, index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  164. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  165. }
  166. glVertexArrayAttribBinding(vao, index, attrib.buffer);
  167. }
  168. }
  169. // Rebinding the VAO invalidates the vertex buffer bindings.
  170. gpu.dirty_flags.vertex_array = 0xFFFFFFFF;
  171. state.draw.vertex_array = vao_entry.handle;
  172. return vao_entry.handle;
  173. }
  174. void RasterizerOpenGL::SetupVertexBuffer(GLuint vao) {
  175. auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  176. const auto& regs = gpu.regs;
  177. if (!gpu.dirty_flags.vertex_array)
  178. return;
  179. MICROPROFILE_SCOPE(OpenGL_VB);
  180. // Upload all guest vertex arrays sequentially to our buffer
  181. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  182. if (~gpu.dirty_flags.vertex_array & (1u << index))
  183. continue;
  184. const auto& vertex_array = regs.vertex_array[index];
  185. if (!vertex_array.IsEnabled())
  186. continue;
  187. const Tegra::GPUVAddr start = vertex_array.StartAddress();
  188. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  189. ASSERT(end > start);
  190. const u64 size = end - start + 1;
  191. const GLintptr vertex_buffer_offset = buffer_cache.UploadMemory(start, size);
  192. // Bind the vertex array to the buffer at the current offset.
  193. glVertexArrayVertexBuffer(vao, index, buffer_cache.GetHandle(), vertex_buffer_offset,
  194. vertex_array.stride);
  195. if (regs.instanced_arrays.IsInstancingEnabled(index) && vertex_array.divisor != 0) {
  196. // Enable vertex buffer instancing with the specified divisor.
  197. glVertexArrayBindingDivisor(vao, index, vertex_array.divisor);
  198. } else {
  199. // Disable the vertex buffer instancing.
  200. glVertexArrayBindingDivisor(vao, index, 0);
  201. }
  202. }
  203. gpu.dirty_flags.vertex_array = 0;
  204. }
  205. DrawParameters RasterizerOpenGL::SetupDraw() {
  206. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  207. const auto& regs = gpu.regs;
  208. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  209. DrawParameters params{};
  210. params.current_instance = gpu.state.current_instance;
  211. if (regs.draw.topology == Maxwell::PrimitiveTopology::Quads) {
  212. MICROPROFILE_SCOPE(OpenGL_PrimitiveAssembly);
  213. params.use_indexed = true;
  214. params.primitive_mode = GL_TRIANGLES;
  215. if (is_indexed) {
  216. params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
  217. params.count = (regs.index_array.count / 4) * 6;
  218. params.index_buffer_offset = primitive_assembler.MakeQuadIndexed(
  219. regs.index_array.IndexStart(), regs.index_array.FormatSizeInBytes(),
  220. regs.index_array.count);
  221. params.base_vertex = static_cast<GLint>(regs.vb_element_base);
  222. } else {
  223. // MakeQuadArray always generates u32 indexes
  224. params.index_format = GL_UNSIGNED_INT;
  225. params.count = (regs.vertex_buffer.count / 4) * 6;
  226. params.index_buffer_offset =
  227. primitive_assembler.MakeQuadArray(regs.vertex_buffer.first, params.count);
  228. }
  229. return params;
  230. }
  231. params.use_indexed = is_indexed;
  232. params.primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
  233. if (is_indexed) {
  234. MICROPROFILE_SCOPE(OpenGL_Index);
  235. params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
  236. params.count = regs.index_array.count;
  237. params.index_buffer_offset =
  238. buffer_cache.UploadMemory(regs.index_array.IndexStart(), CalculateIndexBufferSize());
  239. params.base_vertex = static_cast<GLint>(regs.vb_element_base);
  240. } else {
  241. params.count = regs.vertex_buffer.count;
  242. params.vertex_first = regs.vertex_buffer.first;
  243. }
  244. return params;
  245. }
  246. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  247. MICROPROFILE_SCOPE(OpenGL_Shader);
  248. auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  249. BaseBindings base_bindings;
  250. std::array<bool, Maxwell::NumClipDistances> clip_distances{};
  251. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  252. const auto& shader_config = gpu.regs.shader_config[index];
  253. const Maxwell::ShaderProgram program{static_cast<Maxwell::ShaderProgram>(index)};
  254. // Skip stages that are not enabled
  255. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  256. switch (program) {
  257. case Maxwell::ShaderProgram::Geometry:
  258. shader_program_manager->UseTrivialGeometryShader();
  259. break;
  260. }
  261. continue;
  262. }
  263. const std::size_t stage{index == 0 ? 0 : index - 1}; // Stage indices are 0 - 5
  264. GLShader::MaxwellUniformData ubo{};
  265. ubo.SetFromRegs(gpu.state.shader_stages[stage]);
  266. const GLintptr offset = buffer_cache.UploadHostMemory(
  267. &ubo, sizeof(ubo), static_cast<std::size_t>(uniform_buffer_alignment));
  268. // Bind the emulation info buffer
  269. glBindBufferRange(GL_UNIFORM_BUFFER, base_bindings.cbuf, buffer_cache.GetHandle(), offset,
  270. static_cast<GLsizeiptr>(sizeof(ubo)));
  271. Shader shader{shader_cache.GetStageProgram(program)};
  272. const auto [program_handle, next_bindings] =
  273. shader->GetProgramHandle(primitive_mode, base_bindings);
  274. switch (program) {
  275. case Maxwell::ShaderProgram::VertexA:
  276. case Maxwell::ShaderProgram::VertexB:
  277. shader_program_manager->UseProgrammableVertexShader(program_handle);
  278. break;
  279. case Maxwell::ShaderProgram::Geometry:
  280. shader_program_manager->UseProgrammableGeometryShader(program_handle);
  281. break;
  282. case Maxwell::ShaderProgram::Fragment:
  283. shader_program_manager->UseProgrammableFragmentShader(program_handle);
  284. break;
  285. default:
  286. LOG_CRITICAL(HW_GPU, "Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  287. shader_config.enable.Value(), shader_config.offset);
  288. UNREACHABLE();
  289. }
  290. const auto stage_enum = static_cast<Maxwell::ShaderStage>(stage);
  291. SetupConstBuffers(stage_enum, shader, program_handle, base_bindings);
  292. SetupGlobalRegions(stage_enum, shader, program_handle, base_bindings);
  293. SetupTextures(stage_enum, shader, program_handle, base_bindings);
  294. // Workaround for Intel drivers.
  295. // When a clip distance is enabled but not set in the shader it crops parts of the screen
  296. // (sometimes it's half the screen, sometimes three quarters). To avoid this, enable the
  297. // clip distances only when it's written by a shader stage.
  298. for (std::size_t i = 0; i < Maxwell::NumClipDistances; ++i) {
  299. clip_distances[i] = clip_distances[i] || shader->GetShaderEntries().clip_distances[i];
  300. }
  301. // When VertexA is enabled, we have dual vertex shaders
  302. if (program == Maxwell::ShaderProgram::VertexA) {
  303. // VertexB was combined with VertexA, so we skip the VertexB iteration
  304. index++;
  305. }
  306. base_bindings = next_bindings;
  307. }
  308. SyncClipEnabled(clip_distances);
  309. gpu.dirty_flags.shaders = false;
  310. }
  311. void RasterizerOpenGL::SetupCachedFramebuffer(const FramebufferCacheKey& fbkey,
  312. OpenGLState& current_state) {
  313. const auto [entry, is_cache_miss] = framebuffer_cache.try_emplace(fbkey);
  314. auto& framebuffer = entry->second;
  315. if (is_cache_miss)
  316. framebuffer.Create();
  317. current_state.draw.draw_framebuffer = framebuffer.handle;
  318. current_state.ApplyFramebufferState();
  319. if (!is_cache_miss)
  320. return;
  321. if (fbkey.is_single_buffer) {
  322. if (fbkey.color_attachments[0] != GL_NONE) {
  323. glFramebufferTexture(GL_DRAW_FRAMEBUFFER, fbkey.color_attachments[0], fbkey.colors[0],
  324. 0);
  325. }
  326. glDrawBuffer(fbkey.color_attachments[0]);
  327. } else {
  328. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  329. if (fbkey.colors[index]) {
  330. glFramebufferTexture(GL_DRAW_FRAMEBUFFER,
  331. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index),
  332. fbkey.colors[index], 0);
  333. }
  334. }
  335. glDrawBuffers(fbkey.colors_count, fbkey.color_attachments.data());
  336. }
  337. if (fbkey.zeta) {
  338. GLenum zeta_attachment =
  339. fbkey.stencil_enable ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT;
  340. glFramebufferTexture(GL_DRAW_FRAMEBUFFER, zeta_attachment, fbkey.zeta, 0);
  341. }
  342. }
  343. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  344. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  345. std::size_t size = 0;
  346. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  347. if (!regs.vertex_array[index].IsEnabled())
  348. continue;
  349. const Tegra::GPUVAddr start = regs.vertex_array[index].StartAddress();
  350. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  351. ASSERT(end > start);
  352. size += end - start + 1;
  353. }
  354. return size;
  355. }
  356. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  357. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  358. return static_cast<std::size_t>(regs.index_array.count) *
  359. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  360. }
  361. bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
  362. accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
  363. DrawArrays();
  364. return true;
  365. }
  366. template <typename Map, typename Interval>
  367. static constexpr auto RangeFromInterval(Map& map, const Interval& interval) {
  368. return boost::make_iterator_range(map.equal_range(interval));
  369. }
  370. void RasterizerOpenGL::UpdatePagesCachedCount(Tegra::GPUVAddr addr, u64 size, int delta) {
  371. const u64 page_start{addr >> Memory::PAGE_BITS};
  372. const u64 page_end{(addr + size + Memory::PAGE_SIZE - 1) >> Memory::PAGE_BITS};
  373. // Interval maps will erase segments if count reaches 0, so if delta is negative we have to
  374. // subtract after iterating
  375. const auto pages_interval = CachedPageMap::interval_type::right_open(page_start, page_end);
  376. if (delta > 0)
  377. cached_pages.add({pages_interval, delta});
  378. for (const auto& pair : RangeFromInterval(cached_pages, pages_interval)) {
  379. const auto interval = pair.first & pages_interval;
  380. const int count = pair.second;
  381. const VAddr interval_start_addr = boost::icl::first(interval) << Memory::PAGE_BITS;
  382. const VAddr interval_end_addr = boost::icl::last_next(interval) << Memory::PAGE_BITS;
  383. const u64 interval_size = interval_end_addr - interval_start_addr;
  384. if (delta > 0 && count == delta)
  385. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, true);
  386. else if (delta < 0 && count == -delta)
  387. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, false);
  388. else
  389. ASSERT(count >= 0);
  390. }
  391. if (delta < 0)
  392. cached_pages.add({pages_interval, delta});
  393. }
  394. void RasterizerOpenGL::LoadDiskResources(const std::atomic_bool& stop_loading,
  395. const VideoCore::DiskResourceLoadCallback& callback) {
  396. shader_cache.LoadDiskCache(stop_loading, callback);
  397. }
  398. std::pair<bool, bool> RasterizerOpenGL::ConfigureFramebuffers(
  399. OpenGLState& current_state, bool using_color_fb, bool using_depth_fb, bool preserve_contents,
  400. std::optional<std::size_t> single_color_target) {
  401. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  402. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  403. const auto& regs = gpu.regs;
  404. const FramebufferConfigState fb_config_state{using_color_fb, using_depth_fb, preserve_contents,
  405. single_color_target};
  406. if (fb_config_state == current_framebuffer_config_state && gpu.dirty_flags.color_buffer == 0 &&
  407. !gpu.dirty_flags.zeta_buffer) {
  408. // Only skip if the previous ConfigureFramebuffers call was from the same kind (multiple or
  409. // single color targets). This is done because the guest registers may not change but the
  410. // host framebuffer may contain different attachments
  411. return current_depth_stencil_usage;
  412. }
  413. current_framebuffer_config_state = fb_config_state;
  414. Surface depth_surface;
  415. if (using_depth_fb) {
  416. depth_surface = res_cache.GetDepthBufferSurface(preserve_contents);
  417. }
  418. UNIMPLEMENTED_IF(regs.rt_separate_frag_data == 0);
  419. // Bind the framebuffer surfaces
  420. current_state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0;
  421. FramebufferCacheKey fbkey;
  422. if (using_color_fb) {
  423. if (single_color_target) {
  424. // Used when just a single color attachment is enabled, e.g. for clearing a color buffer
  425. Surface color_surface =
  426. res_cache.GetColorBufferSurface(*single_color_target, preserve_contents);
  427. if (color_surface) {
  428. // Assume that a surface will be written to if it is used as a framebuffer, even if
  429. // the shader doesn't actually write to it.
  430. color_surface->MarkAsModified(true, res_cache);
  431. // Workaround for and issue in nvidia drivers
  432. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  433. state.framebuffer_srgb.enabled |= color_surface->GetSurfaceParams().srgb_conversion;
  434. }
  435. fbkey.is_single_buffer = true;
  436. fbkey.color_attachments[0] =
  437. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target);
  438. fbkey.colors[0] = color_surface != nullptr ? color_surface->Texture().handle : 0;
  439. } else {
  440. // Multiple color attachments are enabled
  441. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  442. Surface color_surface = res_cache.GetColorBufferSurface(index, preserve_contents);
  443. if (color_surface) {
  444. // Assume that a surface will be written to if it is used as a framebuffer, even
  445. // if the shader doesn't actually write to it.
  446. color_surface->MarkAsModified(true, res_cache);
  447. // Enable sRGB only for supported formats
  448. // Workaround for and issue in nvidia drivers
  449. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  450. state.framebuffer_srgb.enabled |=
  451. color_surface->GetSurfaceParams().srgb_conversion;
  452. }
  453. fbkey.color_attachments[index] =
  454. GL_COLOR_ATTACHMENT0 + regs.rt_control.GetMap(index);
  455. fbkey.colors[index] =
  456. color_surface != nullptr ? color_surface->Texture().handle : 0;
  457. }
  458. fbkey.is_single_buffer = false;
  459. fbkey.colors_count = regs.rt_control.count;
  460. }
  461. } else {
  462. // No color attachments are enabled - leave them as zero
  463. fbkey.is_single_buffer = true;
  464. }
  465. if (depth_surface) {
  466. // Assume that a surface will be written to if it is used as a framebuffer, even if
  467. // the shader doesn't actually write to it.
  468. depth_surface->MarkAsModified(true, res_cache);
  469. fbkey.zeta = depth_surface->Texture().handle;
  470. fbkey.stencil_enable = regs.stencil_enable &&
  471. depth_surface->GetSurfaceParams().type == SurfaceType::DepthStencil;
  472. }
  473. SetupCachedFramebuffer(fbkey, current_state);
  474. SyncViewport(current_state);
  475. return current_depth_stencil_usage = {static_cast<bool>(depth_surface), fbkey.stencil_enable};
  476. }
  477. void RasterizerOpenGL::Clear() {
  478. const auto prev_state{state};
  479. SCOPE_EXIT({ prev_state.Apply(); });
  480. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  481. bool use_color{};
  482. bool use_depth{};
  483. bool use_stencil{};
  484. OpenGLState clear_state;
  485. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  486. regs.clear_buffers.A) {
  487. use_color = true;
  488. }
  489. if (use_color) {
  490. clear_state.color_mask[0].red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
  491. clear_state.color_mask[0].green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
  492. clear_state.color_mask[0].blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
  493. clear_state.color_mask[0].alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
  494. }
  495. if (regs.clear_buffers.Z) {
  496. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  497. use_depth = true;
  498. // Always enable the depth write when clearing the depth buffer. The depth write mask is
  499. // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to
  500. // true.
  501. clear_state.depth.test_enabled = true;
  502. clear_state.depth.test_func = GL_ALWAYS;
  503. }
  504. if (regs.clear_buffers.S) {
  505. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear stencil but buffer is not enabled!");
  506. use_stencil = true;
  507. clear_state.stencil.test_enabled = true;
  508. if (regs.clear_flags.stencil) {
  509. // Stencil affects the clear so fill it with the used masks
  510. clear_state.stencil.front.test_func = GL_ALWAYS;
  511. clear_state.stencil.front.test_mask = regs.stencil_front_func_mask;
  512. clear_state.stencil.front.action_stencil_fail = GL_KEEP;
  513. clear_state.stencil.front.action_depth_fail = GL_KEEP;
  514. clear_state.stencil.front.action_depth_pass = GL_KEEP;
  515. clear_state.stencil.front.write_mask = regs.stencil_front_mask;
  516. if (regs.stencil_two_side_enable) {
  517. clear_state.stencil.back.test_func = GL_ALWAYS;
  518. clear_state.stencil.back.test_mask = regs.stencil_back_func_mask;
  519. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  520. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  521. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  522. clear_state.stencil.back.write_mask = regs.stencil_back_mask;
  523. } else {
  524. clear_state.stencil.back.test_func = GL_ALWAYS;
  525. clear_state.stencil.back.test_mask = 0xFFFFFFFF;
  526. clear_state.stencil.back.write_mask = 0xFFFFFFFF;
  527. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  528. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  529. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  530. }
  531. }
  532. }
  533. if (!use_color && !use_depth && !use_stencil) {
  534. // No color surface nor depth/stencil surface are enabled
  535. return;
  536. }
  537. const auto [clear_depth, clear_stencil] = ConfigureFramebuffers(
  538. clear_state, use_color, use_depth || use_stencil, false, regs.clear_buffers.RT.Value());
  539. if (regs.clear_flags.scissor) {
  540. SyncScissorTest(clear_state);
  541. }
  542. if (regs.clear_flags.viewport) {
  543. clear_state.EmulateViewportWithScissor();
  544. }
  545. clear_state.Apply();
  546. if (use_color) {
  547. glClearBufferfv(GL_COLOR, regs.clear_buffers.RT, regs.clear_color);
  548. }
  549. if (clear_depth && clear_stencil) {
  550. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  551. } else if (clear_depth) {
  552. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  553. } else if (clear_stencil) {
  554. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  555. }
  556. }
  557. void RasterizerOpenGL::DrawArrays() {
  558. if (accelerate_draw == AccelDraw::Disabled)
  559. return;
  560. MICROPROFILE_SCOPE(OpenGL_Drawing);
  561. auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  562. const auto& regs = gpu.regs;
  563. ConfigureFramebuffers(state);
  564. SyncColorMask();
  565. SyncFragmentColorClampState();
  566. SyncMultiSampleState();
  567. SyncDepthTestState();
  568. SyncStencilTestState();
  569. SyncBlendState();
  570. SyncLogicOpState();
  571. SyncCullMode();
  572. SyncPrimitiveRestart();
  573. SyncScissorTest(state);
  574. // Alpha Testing is synced on shaders.
  575. SyncTransformFeedback();
  576. SyncPointState();
  577. CheckAlphaTests();
  578. SyncPolygonOffset();
  579. // TODO(bunnei): Sync framebuffer_scale uniform here
  580. // TODO(bunnei): Sync scissorbox uniform(s) here
  581. // Draw the vertex batch
  582. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  583. std::size_t buffer_size = CalculateVertexArraysSize();
  584. // Add space for index buffer (keeping in mind non-core primitives)
  585. switch (regs.draw.topology) {
  586. case Maxwell::PrimitiveTopology::Quads:
  587. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) +
  588. primitive_assembler.CalculateQuadSize(regs.vertex_buffer.count);
  589. break;
  590. default:
  591. if (is_indexed) {
  592. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) + CalculateIndexBufferSize();
  593. }
  594. break;
  595. }
  596. // Uniform space for the 5 shader stages
  597. buffer_size =
  598. Common::AlignUp<std::size_t>(buffer_size, 4) +
  599. (sizeof(GLShader::MaxwellUniformData) + uniform_buffer_alignment) * Maxwell::MaxShaderStage;
  600. // Add space for at least 18 constant buffers
  601. buffer_size += Maxwell::MaxConstBuffers * (MaxConstbufferSize + uniform_buffer_alignment);
  602. bool invalidate = buffer_cache.Map(buffer_size);
  603. if (invalidate) {
  604. // As all cached buffers are invalidated, we need to recheck their state.
  605. gpu.dirty_flags.vertex_array = 0xFFFFFFFF;
  606. }
  607. const GLuint vao = SetupVertexFormat();
  608. SetupVertexBuffer(vao);
  609. DrawParameters params = SetupDraw();
  610. SetupShaders(params.primitive_mode);
  611. buffer_cache.Unmap();
  612. shader_program_manager->ApplyTo(state);
  613. state.Apply();
  614. // Execute draw call
  615. params.DispatchDraw();
  616. // Disable scissor test
  617. state.viewports[0].scissor.enabled = false;
  618. accelerate_draw = AccelDraw::Disabled;
  619. // Unbind textures for potential future use as framebuffer attachments
  620. for (auto& texture_unit : state.texture_units) {
  621. texture_unit.Unbind();
  622. }
  623. state.Apply();
  624. }
  625. void RasterizerOpenGL::FlushAll() {}
  626. void RasterizerOpenGL::FlushRegion(VAddr addr, u64 size) {
  627. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  628. if (Settings::values.use_accurate_gpu_emulation) {
  629. // Only flush if use_accurate_gpu_emulation is enabled, as it incurs a performance hit
  630. res_cache.FlushRegion(addr, size);
  631. }
  632. }
  633. void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size) {
  634. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  635. res_cache.InvalidateRegion(addr, size);
  636. shader_cache.InvalidateRegion(addr, size);
  637. global_cache.InvalidateRegion(addr, size);
  638. buffer_cache.InvalidateRegion(addr, size);
  639. }
  640. void RasterizerOpenGL::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  641. FlushRegion(addr, size);
  642. InvalidateRegion(addr, size);
  643. }
  644. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  645. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  646. const MathUtil::Rectangle<u32>& src_rect,
  647. const MathUtil::Rectangle<u32>& dst_rect) {
  648. MICROPROFILE_SCOPE(OpenGL_Blits);
  649. res_cache.FermiCopySurface(src, dst, src_rect, dst_rect);
  650. return true;
  651. }
  652. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  653. VAddr framebuffer_addr, u32 pixel_stride) {
  654. if (!framebuffer_addr) {
  655. return {};
  656. }
  657. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  658. const auto& surface{res_cache.TryFindFramebufferSurface(framebuffer_addr)};
  659. if (!surface) {
  660. return {};
  661. }
  662. // Verify that the cached surface is the same size and format as the requested framebuffer
  663. const auto& params{surface->GetSurfaceParams()};
  664. const auto& pixel_format{
  665. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  666. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  667. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  668. ASSERT_MSG(params.pixel_format == pixel_format, "Framebuffer pixel_format is different");
  669. screen_info.display_texture = surface->Texture().handle;
  670. return true;
  671. }
  672. void RasterizerOpenGL::SamplerInfo::Create() {
  673. sampler.Create();
  674. mag_filter = min_filter = Tegra::Texture::TextureFilter::Linear;
  675. wrap_u = wrap_v = wrap_p = Tegra::Texture::WrapMode::Wrap;
  676. uses_depth_compare = false;
  677. depth_compare_func = Tegra::Texture::DepthCompareFunc::Never;
  678. // default is GL_LINEAR_MIPMAP_LINEAR
  679. glSamplerParameteri(sampler.handle, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  680. // Other attributes have correct defaults
  681. glSamplerParameteri(sampler.handle, GL_TEXTURE_COMPARE_FUNC, GL_NEVER);
  682. }
  683. void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntry& config) {
  684. const GLuint s = sampler.handle;
  685. if (mag_filter != config.mag_filter) {
  686. mag_filter = config.mag_filter;
  687. glSamplerParameteri(
  688. s, GL_TEXTURE_MAG_FILTER,
  689. MaxwellToGL::TextureFilterMode(mag_filter, Tegra::Texture::TextureMipmapFilter::None));
  690. }
  691. if (min_filter != config.min_filter || mip_filter != config.mip_filter) {
  692. min_filter = config.min_filter;
  693. mip_filter = config.mip_filter;
  694. glSamplerParameteri(s, GL_TEXTURE_MIN_FILTER,
  695. MaxwellToGL::TextureFilterMode(min_filter, mip_filter));
  696. }
  697. if (wrap_u != config.wrap_u) {
  698. wrap_u = config.wrap_u;
  699. glSamplerParameteri(s, GL_TEXTURE_WRAP_S, MaxwellToGL::WrapMode(wrap_u));
  700. }
  701. if (wrap_v != config.wrap_v) {
  702. wrap_v = config.wrap_v;
  703. glSamplerParameteri(s, GL_TEXTURE_WRAP_T, MaxwellToGL::WrapMode(wrap_v));
  704. }
  705. if (wrap_p != config.wrap_p) {
  706. wrap_p = config.wrap_p;
  707. glSamplerParameteri(s, GL_TEXTURE_WRAP_R, MaxwellToGL::WrapMode(wrap_p));
  708. }
  709. if (uses_depth_compare != (config.depth_compare_enabled == 1)) {
  710. uses_depth_compare = (config.depth_compare_enabled == 1);
  711. if (uses_depth_compare) {
  712. glSamplerParameteri(s, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  713. } else {
  714. glSamplerParameteri(s, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  715. }
  716. }
  717. if (depth_compare_func != config.depth_compare_func) {
  718. depth_compare_func = config.depth_compare_func;
  719. glSamplerParameteri(s, GL_TEXTURE_COMPARE_FUNC,
  720. MaxwellToGL::DepthCompareFunc(depth_compare_func));
  721. }
  722. GLvec4 new_border_color;
  723. if (config.srgb_conversion) {
  724. new_border_color[0] = config.srgb_border_color_r / 255.0f;
  725. new_border_color[1] = config.srgb_border_color_g / 255.0f;
  726. new_border_color[2] = config.srgb_border_color_g / 255.0f;
  727. } else {
  728. new_border_color[0] = config.border_color_r;
  729. new_border_color[1] = config.border_color_g;
  730. new_border_color[2] = config.border_color_b;
  731. }
  732. new_border_color[3] = config.border_color_a;
  733. if (border_color != new_border_color) {
  734. border_color = new_border_color;
  735. glSamplerParameterfv(s, GL_TEXTURE_BORDER_COLOR, border_color.data());
  736. }
  737. const float anisotropic_max = static_cast<float>(1 << config.max_anisotropy.Value());
  738. if (anisotropic_max != max_anisotropic) {
  739. max_anisotropic = anisotropic_max;
  740. if (GLAD_GL_ARB_texture_filter_anisotropic) {
  741. glSamplerParameterf(s, GL_TEXTURE_MAX_ANISOTROPY, max_anisotropic);
  742. } else if (GLAD_GL_EXT_texture_filter_anisotropic) {
  743. glSamplerParameterf(s, GL_TEXTURE_MAX_ANISOTROPY_EXT, max_anisotropic);
  744. }
  745. }
  746. const float lod_min = static_cast<float>(config.min_lod_clamp.Value()) / 256.0f;
  747. if (lod_min != min_lod) {
  748. min_lod = lod_min;
  749. glSamplerParameterf(s, GL_TEXTURE_MIN_LOD, min_lod);
  750. }
  751. const float lod_max = static_cast<float>(config.max_lod_clamp.Value()) / 256.0f;
  752. if (lod_max != max_lod) {
  753. max_lod = lod_max;
  754. glSamplerParameterf(s, GL_TEXTURE_MAX_LOD, max_lod);
  755. }
  756. const u32 bias = config.mip_lod_bias.Value();
  757. // Sign extend the 13-bit value.
  758. constexpr u32 mask = 1U << (13 - 1);
  759. const float bias_lod = static_cast<s32>((bias ^ mask) - mask) / 256.f;
  760. if (lod_bias != bias_lod) {
  761. lod_bias = bias_lod;
  762. glSamplerParameterf(s, GL_TEXTURE_LOD_BIAS, lod_bias);
  763. }
  764. }
  765. void RasterizerOpenGL::SetupConstBuffers(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
  766. const Shader& shader, GLuint program_handle,
  767. BaseBindings base_bindings) {
  768. MICROPROFILE_SCOPE(OpenGL_UBO);
  769. const auto& gpu = Core::System::GetInstance().GPU();
  770. const auto& maxwell3d = gpu.Maxwell3D();
  771. const auto& shader_stage = maxwell3d.state.shader_stages[static_cast<std::size_t>(stage)];
  772. const auto& entries = shader->GetShaderEntries().const_buffers;
  773. constexpr u64 max_binds = Tegra::Engines::Maxwell3D::Regs::MaxConstBuffers;
  774. std::array<GLuint, max_binds> bind_buffers;
  775. std::array<GLintptr, max_binds> bind_offsets;
  776. std::array<GLsizeiptr, max_binds> bind_sizes;
  777. ASSERT_MSG(entries.size() <= max_binds, "Exceeded expected number of binding points.");
  778. // Upload only the enabled buffers from the 16 constbuffers of each shader stage
  779. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  780. const auto& used_buffer = entries[bindpoint];
  781. const auto& buffer = shader_stage.const_buffers[used_buffer.GetIndex()];
  782. if (!buffer.enabled) {
  783. // With disabled buffers set values as zero to unbind them
  784. bind_buffers[bindpoint] = 0;
  785. bind_offsets[bindpoint] = 0;
  786. bind_sizes[bindpoint] = 0;
  787. continue;
  788. }
  789. std::size_t size = 0;
  790. if (used_buffer.IsIndirect()) {
  791. // Buffer is accessed indirectly, so upload the entire thing
  792. size = buffer.size;
  793. if (size > MaxConstbufferSize) {
  794. LOG_CRITICAL(HW_GPU, "indirect constbuffer size {} exceeds maximum {}", size,
  795. MaxConstbufferSize);
  796. size = MaxConstbufferSize;
  797. }
  798. } else {
  799. // Buffer is accessed directly, upload just what we use
  800. size = used_buffer.GetSize();
  801. }
  802. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  803. // UBO alignment requirements.
  804. size = Common::AlignUp(size, sizeof(GLvec4));
  805. ASSERT_MSG(size <= MaxConstbufferSize, "Constbuffer too big");
  806. const GLintptr const_buffer_offset = buffer_cache.UploadMemory(
  807. buffer.address, size, static_cast<std::size_t>(uniform_buffer_alignment));
  808. // Prepare values for multibind
  809. bind_buffers[bindpoint] = buffer_cache.GetHandle();
  810. bind_offsets[bindpoint] = const_buffer_offset;
  811. bind_sizes[bindpoint] = size;
  812. }
  813. // The first binding is reserved for emulation values
  814. const GLuint ubo_base_binding = base_bindings.cbuf + 1;
  815. glBindBuffersRange(GL_UNIFORM_BUFFER, ubo_base_binding, static_cast<GLsizei>(entries.size()),
  816. bind_buffers.data(), bind_offsets.data(), bind_sizes.data());
  817. }
  818. void RasterizerOpenGL::SetupGlobalRegions(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
  819. const Shader& shader, GLenum primitive_mode,
  820. BaseBindings base_bindings) {
  821. // TODO(Rodrigo): Use ARB_multi_bind here
  822. const auto& entries = shader->GetShaderEntries().global_memory_entries;
  823. for (u32 bindpoint = 0; bindpoint < static_cast<u32>(entries.size()); ++bindpoint) {
  824. const auto& entry = entries[bindpoint];
  825. const u32 current_bindpoint = base_bindings.gmem + bindpoint;
  826. const auto& region = global_cache.GetGlobalRegion(entry, stage);
  827. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, current_bindpoint, region->GetBufferHandle());
  828. }
  829. }
  830. void RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, const Shader& shader,
  831. GLuint program_handle, BaseBindings base_bindings) {
  832. MICROPROFILE_SCOPE(OpenGL_Texture);
  833. const auto& gpu = Core::System::GetInstance().GPU();
  834. const auto& maxwell3d = gpu.Maxwell3D();
  835. const auto& entries = shader->GetShaderEntries().samplers;
  836. ASSERT_MSG(base_bindings.sampler + entries.size() <= std::size(state.texture_units),
  837. "Exceeded the number of active textures.");
  838. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  839. const auto& entry = entries[bindpoint];
  840. const auto texture = maxwell3d.GetStageTexture(stage, entry.GetOffset());
  841. const u32 current_bindpoint = base_bindings.sampler + bindpoint;
  842. texture_samplers[current_bindpoint].SyncWithConfig(texture.tsc);
  843. Surface surface = res_cache.GetTextureSurface(texture, entry);
  844. if (surface != nullptr) {
  845. state.texture_units[current_bindpoint].texture =
  846. entry.IsArray() ? surface->TextureLayer().handle : surface->Texture().handle;
  847. surface->UpdateSwizzle(texture.tic.x_source, texture.tic.y_source, texture.tic.z_source,
  848. texture.tic.w_source);
  849. } else {
  850. // Can occur when texture addr is null or its memory is unmapped/invalid
  851. state.texture_units[current_bindpoint].texture = 0;
  852. }
  853. }
  854. }
  855. void RasterizerOpenGL::SyncViewport(OpenGLState& current_state) {
  856. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  857. const bool geometry_shaders_enabled =
  858. regs.IsShaderConfigEnabled(static_cast<size_t>(Maxwell::ShaderProgram::Geometry));
  859. const std::size_t viewport_count =
  860. geometry_shaders_enabled ? Tegra::Engines::Maxwell3D::Regs::NumViewports : 1;
  861. for (std::size_t i = 0; i < viewport_count; i++) {
  862. auto& viewport = current_state.viewports[i];
  863. const auto& src = regs.viewports[i];
  864. const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[i].GetRect()};
  865. viewport.x = viewport_rect.left;
  866. viewport.y = viewport_rect.bottom;
  867. viewport.width = viewport_rect.GetWidth();
  868. viewport.height = viewport_rect.GetHeight();
  869. viewport.depth_range_far = regs.viewports[i].depth_range_far;
  870. viewport.depth_range_near = regs.viewports[i].depth_range_near;
  871. }
  872. state.depth_clamp.far_plane = regs.view_volume_clip_control.depth_clamp_far != 0;
  873. state.depth_clamp.near_plane = regs.view_volume_clip_control.depth_clamp_near != 0;
  874. }
  875. void RasterizerOpenGL::SyncClipEnabled(
  876. const std::array<bool, Maxwell::Regs::NumClipDistances>& clip_mask) {
  877. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  878. const std::array<bool, Maxwell::Regs::NumClipDistances> reg_state{
  879. regs.clip_distance_enabled.c0 != 0, regs.clip_distance_enabled.c1 != 0,
  880. regs.clip_distance_enabled.c2 != 0, regs.clip_distance_enabled.c3 != 0,
  881. regs.clip_distance_enabled.c4 != 0, regs.clip_distance_enabled.c5 != 0,
  882. regs.clip_distance_enabled.c6 != 0, regs.clip_distance_enabled.c7 != 0};
  883. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  884. state.clip_distance[i] = reg_state[i] && clip_mask[i];
  885. }
  886. }
  887. void RasterizerOpenGL::SyncClipCoef() {
  888. UNIMPLEMENTED();
  889. }
  890. void RasterizerOpenGL::SyncCullMode() {
  891. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  892. state.cull.enabled = regs.cull.enabled != 0;
  893. if (state.cull.enabled) {
  894. state.cull.front_face = MaxwellToGL::FrontFace(regs.cull.front_face);
  895. state.cull.mode = MaxwellToGL::CullFace(regs.cull.cull_face);
  896. const bool flip_triangles{regs.screen_y_control.triangle_rast_flip == 0 ||
  897. regs.viewport_transform[0].scale_y < 0.0f};
  898. // If the GPU is configured to flip the rasterized triangles, then we need to flip the
  899. // notion of front and back. Note: We flip the triangles when the value of the register is 0
  900. // because OpenGL already does it for us.
  901. if (flip_triangles) {
  902. if (state.cull.front_face == GL_CCW)
  903. state.cull.front_face = GL_CW;
  904. else if (state.cull.front_face == GL_CW)
  905. state.cull.front_face = GL_CCW;
  906. }
  907. }
  908. }
  909. void RasterizerOpenGL::SyncPrimitiveRestart() {
  910. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  911. state.primitive_restart.enabled = regs.primitive_restart.enabled;
  912. state.primitive_restart.index = regs.primitive_restart.index;
  913. }
  914. void RasterizerOpenGL::SyncDepthTestState() {
  915. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  916. state.depth.test_enabled = regs.depth_test_enable != 0;
  917. state.depth.write_mask = regs.depth_write_enabled ? GL_TRUE : GL_FALSE;
  918. if (!state.depth.test_enabled)
  919. return;
  920. state.depth.test_func = MaxwellToGL::ComparisonOp(regs.depth_test_func);
  921. }
  922. void RasterizerOpenGL::SyncStencilTestState() {
  923. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  924. state.stencil.test_enabled = regs.stencil_enable != 0;
  925. if (!regs.stencil_enable) {
  926. return;
  927. }
  928. state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func);
  929. state.stencil.front.test_ref = regs.stencil_front_func_ref;
  930. state.stencil.front.test_mask = regs.stencil_front_func_mask;
  931. state.stencil.front.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_fail);
  932. state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail);
  933. state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass);
  934. state.stencil.front.write_mask = regs.stencil_front_mask;
  935. if (regs.stencil_two_side_enable) {
  936. state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
  937. state.stencil.back.test_ref = regs.stencil_back_func_ref;
  938. state.stencil.back.test_mask = regs.stencil_back_func_mask;
  939. state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
  940. state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
  941. state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
  942. state.stencil.back.write_mask = regs.stencil_back_mask;
  943. } else {
  944. state.stencil.back.test_func = GL_ALWAYS;
  945. state.stencil.back.test_ref = 0;
  946. state.stencil.back.test_mask = 0xFFFFFFFF;
  947. state.stencil.back.write_mask = 0xFFFFFFFF;
  948. state.stencil.back.action_stencil_fail = GL_KEEP;
  949. state.stencil.back.action_depth_fail = GL_KEEP;
  950. state.stencil.back.action_depth_pass = GL_KEEP;
  951. }
  952. }
  953. void RasterizerOpenGL::SyncColorMask() {
  954. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  955. const std::size_t count =
  956. regs.independent_blend_enable ? Tegra::Engines::Maxwell3D::Regs::NumRenderTargets : 1;
  957. for (std::size_t i = 0; i < count; i++) {
  958. const auto& source = regs.color_mask[regs.color_mask_common ? 0 : i];
  959. auto& dest = state.color_mask[i];
  960. dest.red_enabled = (source.R == 0) ? GL_FALSE : GL_TRUE;
  961. dest.green_enabled = (source.G == 0) ? GL_FALSE : GL_TRUE;
  962. dest.blue_enabled = (source.B == 0) ? GL_FALSE : GL_TRUE;
  963. dest.alpha_enabled = (source.A == 0) ? GL_FALSE : GL_TRUE;
  964. }
  965. }
  966. void RasterizerOpenGL::SyncMultiSampleState() {
  967. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  968. state.multisample_control.alpha_to_coverage = regs.multisample_control.alpha_to_coverage != 0;
  969. state.multisample_control.alpha_to_one = regs.multisample_control.alpha_to_one != 0;
  970. }
  971. void RasterizerOpenGL::SyncFragmentColorClampState() {
  972. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  973. state.fragment_color_clamp.enabled = regs.frag_color_clamp != 0;
  974. }
  975. void RasterizerOpenGL::SyncBlendState() {
  976. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  977. state.blend_color.red = regs.blend_color.r;
  978. state.blend_color.green = regs.blend_color.g;
  979. state.blend_color.blue = regs.blend_color.b;
  980. state.blend_color.alpha = regs.blend_color.a;
  981. state.independant_blend.enabled = regs.independent_blend_enable;
  982. if (!state.independant_blend.enabled) {
  983. auto& blend = state.blend[0];
  984. const auto& src = regs.blend;
  985. blend.enabled = src.enable[0] != 0;
  986. if (blend.enabled) {
  987. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  988. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  989. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  990. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  991. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  992. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  993. }
  994. for (std::size_t i = 1; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  995. state.blend[i].enabled = false;
  996. }
  997. return;
  998. }
  999. for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  1000. auto& blend = state.blend[i];
  1001. const auto& src = regs.independent_blend[i];
  1002. blend.enabled = regs.blend.enable[i] != 0;
  1003. if (!blend.enabled)
  1004. continue;
  1005. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  1006. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  1007. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  1008. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  1009. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  1010. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  1011. }
  1012. }
  1013. void RasterizerOpenGL::SyncLogicOpState() {
  1014. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  1015. state.logic_op.enabled = regs.logic_op.enable != 0;
  1016. if (!state.logic_op.enabled)
  1017. return;
  1018. ASSERT_MSG(regs.blend.enable[0] == 0,
  1019. "Blending and logic op can't be enabled at the same time.");
  1020. state.logic_op.operation = MaxwellToGL::LogicOp(regs.logic_op.operation);
  1021. }
  1022. void RasterizerOpenGL::SyncScissorTest(OpenGLState& current_state) {
  1023. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  1024. const bool geometry_shaders_enabled =
  1025. regs.IsShaderConfigEnabled(static_cast<size_t>(Maxwell::ShaderProgram::Geometry));
  1026. const std::size_t viewport_count =
  1027. geometry_shaders_enabled ? Tegra::Engines::Maxwell3D::Regs::NumViewports : 1;
  1028. for (std::size_t i = 0; i < viewport_count; i++) {
  1029. const auto& src = regs.scissor_test[i];
  1030. auto& dst = current_state.viewports[i].scissor;
  1031. dst.enabled = (src.enable != 0);
  1032. if (dst.enabled == 0) {
  1033. return;
  1034. }
  1035. const u32 width = src.max_x - src.min_x;
  1036. const u32 height = src.max_y - src.min_y;
  1037. dst.x = src.min_x;
  1038. dst.y = src.min_y;
  1039. dst.width = width;
  1040. dst.height = height;
  1041. }
  1042. }
  1043. void RasterizerOpenGL::SyncTransformFeedback() {
  1044. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  1045. if (regs.tfb_enabled != 0) {
  1046. LOG_CRITICAL(Render_OpenGL, "Transform feedbacks are not implemented");
  1047. UNREACHABLE();
  1048. }
  1049. }
  1050. void RasterizerOpenGL::SyncPointState() {
  1051. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  1052. state.point.size = regs.point_size;
  1053. }
  1054. void RasterizerOpenGL::SyncPolygonOffset() {
  1055. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  1056. state.polygon_offset.fill_enable = regs.polygon_offset_fill_enable != 0;
  1057. state.polygon_offset.line_enable = regs.polygon_offset_line_enable != 0;
  1058. state.polygon_offset.point_enable = regs.polygon_offset_point_enable != 0;
  1059. state.polygon_offset.units = regs.polygon_offset_units;
  1060. state.polygon_offset.factor = regs.polygon_offset_factor;
  1061. state.polygon_offset.clamp = regs.polygon_offset_clamp;
  1062. }
  1063. void RasterizerOpenGL::CheckAlphaTests() {
  1064. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  1065. if (regs.alpha_test_enabled != 0 && regs.rt_control.count > 1) {
  1066. LOG_CRITICAL(Render_OpenGL, "Alpha Testing is enabled with Multiple Render Targets, "
  1067. "this behavior is undefined.");
  1068. UNREACHABLE();
  1069. }
  1070. }
  1071. } // namespace OpenGL