gl_rasterizer.cpp 47 KB

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