gl_rasterizer.cpp 47 KB

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