gl_rasterizer.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  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 <bitset>
  7. #include <memory>
  8. #include <string>
  9. #include <string_view>
  10. #include <tuple>
  11. #include <utility>
  12. #include <glad/glad.h>
  13. #include "common/alignment.h"
  14. #include "common/assert.h"
  15. #include "common/logging/log.h"
  16. #include "common/math_util.h"
  17. #include "common/microprofile.h"
  18. #include "common/scope_exit.h"
  19. #include "core/core.h"
  20. #include "core/hle/kernel/process.h"
  21. #include "core/memory.h"
  22. #include "core/settings.h"
  23. #include "video_core/engines/kepler_compute.h"
  24. #include "video_core/engines/maxwell_3d.h"
  25. #include "video_core/engines/shader_type.h"
  26. #include "video_core/memory_manager.h"
  27. #include "video_core/renderer_opengl/gl_query_cache.h"
  28. #include "video_core/renderer_opengl/gl_rasterizer.h"
  29. #include "video_core/renderer_opengl/gl_shader_cache.h"
  30. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  31. #include "video_core/renderer_opengl/renderer_opengl.h"
  32. namespace OpenGL {
  33. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  34. using Tegra::Engines::ShaderType;
  35. using VideoCore::Surface::PixelFormat;
  36. using VideoCore::Surface::SurfaceTarget;
  37. using VideoCore::Surface::SurfaceType;
  38. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Format Setup", MP_RGB(128, 128, 192));
  39. MICROPROFILE_DEFINE(OpenGL_VB, "OpenGL", "Vertex Buffer Setup", MP_RGB(128, 128, 192));
  40. MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192));
  41. MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192));
  42. MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192));
  43. MICROPROFILE_DEFINE(OpenGL_Texture, "OpenGL", "Texture Setup", MP_RGB(128, 128, 192));
  44. MICROPROFILE_DEFINE(OpenGL_Framebuffer, "OpenGL", "Framebuffer Setup", MP_RGB(128, 128, 192));
  45. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  46. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
  47. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
  48. MICROPROFILE_DEFINE(OpenGL_PrimitiveAssembly, "OpenGL", "Prim Asmbl", MP_RGB(255, 100, 100));
  49. namespace {
  50. constexpr std::size_t NumSupportedVertexAttributes = 16;
  51. template <typename Engine, typename Entry>
  52. Tegra::Texture::FullTextureInfo GetTextureInfo(const Engine& engine, const Entry& entry,
  53. ShaderType shader_type, std::size_t index = 0) {
  54. if (entry.IsBindless()) {
  55. const Tegra::Texture::TextureHandle tex_handle =
  56. engine.AccessConstBuffer32(shader_type, entry.GetBuffer(), entry.GetOffset());
  57. return engine.GetTextureInfo(tex_handle);
  58. }
  59. const auto& gpu_profile = engine.AccessGuestDriverProfile();
  60. const u32 offset =
  61. entry.GetOffset() + static_cast<u32>(index * gpu_profile.GetTextureHandlerSize());
  62. if constexpr (std::is_same_v<Engine, Tegra::Engines::Maxwell3D>) {
  63. return engine.GetStageTexture(shader_type, offset);
  64. } else {
  65. return engine.GetTexture(offset);
  66. }
  67. }
  68. std::size_t GetConstBufferSize(const Tegra::Engines::ConstBufferInfo& buffer,
  69. const ConstBufferEntry& entry) {
  70. if (!entry.IsIndirect()) {
  71. return entry.GetSize();
  72. }
  73. if (buffer.size > Maxwell::MaxConstBufferSize) {
  74. LOG_WARNING(Render_OpenGL, "Indirect constbuffer size {} exceeds maximum {}", buffer.size,
  75. Maxwell::MaxConstBufferSize);
  76. return Maxwell::MaxConstBufferSize;
  77. }
  78. return buffer.size;
  79. }
  80. void oglEnable(GLenum cap, bool state) {
  81. (state ? glEnable : glDisable)(cap);
  82. }
  83. } // Anonymous namespace
  84. RasterizerOpenGL::RasterizerOpenGL(Core::System& system, Core::Frontend::EmuWindow& emu_window,
  85. ScreenInfo& info, GLShader::ProgramManager& program_manager,
  86. StateTracker& state_tracker)
  87. : RasterizerAccelerated{system.Memory()}, texture_cache{system, *this, device, state_tracker},
  88. shader_cache{*this, system, emu_window, device}, query_cache{system, *this}, system{system},
  89. screen_info{info}, program_manager{program_manager}, state_tracker{state_tracker},
  90. buffer_cache{*this, system, device, STREAM_BUFFER_SIZE}, fence_manager{system, *this,
  91. texture_cache} {
  92. CheckExtensions();
  93. }
  94. RasterizerOpenGL::~RasterizerOpenGL() {}
  95. void RasterizerOpenGL::CheckExtensions() {
  96. if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
  97. LOG_WARNING(
  98. Render_OpenGL,
  99. "Anisotropic filter is not supported! This can cause graphical issues in some games.");
  100. }
  101. }
  102. void RasterizerOpenGL::SetupVertexFormat() {
  103. auto& gpu = system.GPU().Maxwell3D();
  104. auto& flags = gpu.dirty.flags;
  105. if (!flags[Dirty::VertexFormats]) {
  106. return;
  107. }
  108. flags[Dirty::VertexFormats] = false;
  109. MICROPROFILE_SCOPE(OpenGL_VAO);
  110. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL. Enables
  111. // the first 16 vertex attributes always, as we don't know which ones are actually used until
  112. // shader time. Note, Tegra technically supports 32, but we're capping this to 16 for now to
  113. // avoid OpenGL errors.
  114. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  115. // assume every shader uses them all.
  116. for (std::size_t index = 0; index < NumSupportedVertexAttributes; ++index) {
  117. if (!flags[Dirty::VertexFormat0 + index]) {
  118. continue;
  119. }
  120. flags[Dirty::VertexFormat0 + index] = false;
  121. const auto attrib = gpu.regs.vertex_attrib_format[index];
  122. const auto gl_index = static_cast<GLuint>(index);
  123. // Disable constant attributes.
  124. if (attrib.IsConstant()) {
  125. glDisableVertexAttribArray(gl_index);
  126. continue;
  127. }
  128. glEnableVertexAttribArray(gl_index);
  129. if (attrib.type == Maxwell::VertexAttribute::Type::SignedInt ||
  130. attrib.type == Maxwell::VertexAttribute::Type::UnsignedInt) {
  131. glVertexAttribIFormat(gl_index, attrib.ComponentCount(),
  132. MaxwellToGL::VertexType(attrib), attrib.offset);
  133. } else {
  134. glVertexAttribFormat(gl_index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  135. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  136. }
  137. glVertexAttribBinding(gl_index, attrib.buffer);
  138. }
  139. }
  140. void RasterizerOpenGL::SetupVertexBuffer() {
  141. auto& gpu = system.GPU().Maxwell3D();
  142. auto& flags = gpu.dirty.flags;
  143. if (!flags[Dirty::VertexBuffers]) {
  144. return;
  145. }
  146. flags[Dirty::VertexBuffers] = false;
  147. MICROPROFILE_SCOPE(OpenGL_VB);
  148. // Upload all guest vertex arrays sequentially to our buffer
  149. const auto& regs = gpu.regs;
  150. for (std::size_t index = 0; index < Maxwell::NumVertexArrays; ++index) {
  151. if (!flags[Dirty::VertexBuffer0 + index]) {
  152. continue;
  153. }
  154. flags[Dirty::VertexBuffer0 + index] = false;
  155. const auto& vertex_array = regs.vertex_array[index];
  156. if (!vertex_array.IsEnabled()) {
  157. continue;
  158. }
  159. const GPUVAddr start = vertex_array.StartAddress();
  160. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  161. ASSERT(end > start);
  162. const u64 size = end - start + 1;
  163. const auto [vertex_buffer, vertex_buffer_offset] = buffer_cache.UploadMemory(start, size);
  164. glBindVertexBuffer(static_cast<GLuint>(index), vertex_buffer, vertex_buffer_offset,
  165. vertex_array.stride);
  166. }
  167. }
  168. void RasterizerOpenGL::SetupVertexInstances() {
  169. auto& gpu = system.GPU().Maxwell3D();
  170. auto& flags = gpu.dirty.flags;
  171. if (!flags[Dirty::VertexInstances]) {
  172. return;
  173. }
  174. flags[Dirty::VertexInstances] = false;
  175. const auto& regs = gpu.regs;
  176. for (std::size_t index = 0; index < NumSupportedVertexAttributes; ++index) {
  177. if (!flags[Dirty::VertexInstance0 + index]) {
  178. continue;
  179. }
  180. flags[Dirty::VertexInstance0 + index] = false;
  181. const auto gl_index = static_cast<GLuint>(index);
  182. const bool instancing_enabled = regs.instanced_arrays.IsInstancingEnabled(gl_index);
  183. const GLuint divisor = instancing_enabled ? regs.vertex_array[index].divisor : 0;
  184. glVertexBindingDivisor(gl_index, divisor);
  185. }
  186. }
  187. GLintptr RasterizerOpenGL::SetupIndexBuffer() {
  188. MICROPROFILE_SCOPE(OpenGL_Index);
  189. const auto& regs = system.GPU().Maxwell3D().regs;
  190. const std::size_t size = CalculateIndexBufferSize();
  191. const auto [buffer, offset] = buffer_cache.UploadMemory(regs.index_array.IndexStart(), size);
  192. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer);
  193. return offset;
  194. }
  195. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  196. MICROPROFILE_SCOPE(OpenGL_Shader);
  197. auto& gpu = system.GPU().Maxwell3D();
  198. u32 clip_distances = 0;
  199. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  200. const auto& shader_config = gpu.regs.shader_config[index];
  201. const auto program{static_cast<Maxwell::ShaderProgram>(index)};
  202. // Skip stages that are not enabled
  203. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  204. switch (program) {
  205. case Maxwell::ShaderProgram::Geometry:
  206. program_manager.UseGeometryShader(0);
  207. break;
  208. case Maxwell::ShaderProgram::Fragment:
  209. program_manager.UseFragmentShader(0);
  210. break;
  211. default:
  212. break;
  213. }
  214. continue;
  215. }
  216. // Currently this stages are not supported in the OpenGL backend.
  217. // Todo(Blinkhawk): Port tesselation shaders from Vulkan to OpenGL
  218. if (program == Maxwell::ShaderProgram::TesselationControl) {
  219. continue;
  220. } else if (program == Maxwell::ShaderProgram::TesselationEval) {
  221. continue;
  222. }
  223. Shader shader{shader_cache.GetStageProgram(program)};
  224. // Stage indices are 0 - 5
  225. const std::size_t stage = index == 0 ? 0 : index - 1;
  226. SetupDrawConstBuffers(stage, shader);
  227. SetupDrawGlobalMemory(stage, shader);
  228. SetupDrawTextures(stage, shader);
  229. SetupDrawImages(stage, shader);
  230. const GLuint program_handle = shader->GetHandle();
  231. switch (program) {
  232. case Maxwell::ShaderProgram::VertexA:
  233. case Maxwell::ShaderProgram::VertexB:
  234. program_manager.UseVertexShader(program_handle);
  235. break;
  236. case Maxwell::ShaderProgram::Geometry:
  237. program_manager.UseGeometryShader(program_handle);
  238. break;
  239. case Maxwell::ShaderProgram::Fragment:
  240. program_manager.UseFragmentShader(program_handle);
  241. break;
  242. default:
  243. UNIMPLEMENTED_MSG("Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  244. shader_config.enable.Value(), shader_config.offset);
  245. }
  246. // Workaround for Intel drivers.
  247. // When a clip distance is enabled but not set in the shader it crops parts of the screen
  248. // (sometimes it's half the screen, sometimes three quarters). To avoid this, enable the
  249. // clip distances only when it's written by a shader stage.
  250. clip_distances |= shader->GetEntries().clip_distances;
  251. // When VertexA is enabled, we have dual vertex shaders
  252. if (program == Maxwell::ShaderProgram::VertexA) {
  253. // VertexB was combined with VertexA, so we skip the VertexB iteration
  254. ++index;
  255. }
  256. }
  257. SyncClipEnabled(clip_distances);
  258. gpu.dirty.flags[Dirty::Shaders] = false;
  259. }
  260. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  261. const auto& regs = system.GPU().Maxwell3D().regs;
  262. std::size_t size = 0;
  263. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  264. if (!regs.vertex_array[index].IsEnabled())
  265. continue;
  266. const GPUVAddr start = regs.vertex_array[index].StartAddress();
  267. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  268. ASSERT(end > start);
  269. size += end - start + 1;
  270. }
  271. return size;
  272. }
  273. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  274. const auto& regs = system.GPU().Maxwell3D().regs;
  275. return static_cast<std::size_t>(regs.index_array.count) *
  276. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  277. }
  278. void RasterizerOpenGL::LoadDiskResources(const std::atomic_bool& stop_loading,
  279. const VideoCore::DiskResourceLoadCallback& callback) {
  280. shader_cache.LoadDiskCache(stop_loading, callback);
  281. }
  282. void RasterizerOpenGL::SetupDirtyFlags() {
  283. state_tracker.Initialize();
  284. }
  285. void RasterizerOpenGL::ConfigureFramebuffers() {
  286. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  287. auto& gpu = system.GPU().Maxwell3D();
  288. if (!gpu.dirty.flags[VideoCommon::Dirty::RenderTargets]) {
  289. return;
  290. }
  291. gpu.dirty.flags[VideoCommon::Dirty::RenderTargets] = false;
  292. texture_cache.GuardRenderTargets(true);
  293. View depth_surface = texture_cache.GetDepthBufferSurface();
  294. const auto& regs = gpu.regs;
  295. UNIMPLEMENTED_IF(regs.rt_separate_frag_data == 0);
  296. // Bind the framebuffer surfaces
  297. FramebufferCacheKey key;
  298. const auto colors_count = static_cast<std::size_t>(regs.rt_control.count);
  299. for (std::size_t index = 0; index < colors_count; ++index) {
  300. View color_surface{texture_cache.GetColorBufferSurface(index)};
  301. if (!color_surface) {
  302. continue;
  303. }
  304. // Assume that a surface will be written to if it is used as a framebuffer, even
  305. // if the shader doesn't actually write to it.
  306. texture_cache.MarkColorBufferInUse(index);
  307. key.SetAttachment(index, regs.rt_control.GetMap(index));
  308. key.colors[index] = std::move(color_surface);
  309. }
  310. if (depth_surface) {
  311. // Assume that a surface will be written to if it is used as a framebuffer, even if
  312. // the shader doesn't actually write to it.
  313. texture_cache.MarkDepthBufferInUse();
  314. key.zeta = std::move(depth_surface);
  315. }
  316. texture_cache.GuardRenderTargets(false);
  317. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer_cache.GetFramebuffer(key));
  318. }
  319. void RasterizerOpenGL::ConfigureClearFramebuffer(bool using_color_fb, bool using_depth_fb,
  320. bool using_stencil_fb) {
  321. auto& gpu = system.GPU().Maxwell3D();
  322. const auto& regs = gpu.regs;
  323. texture_cache.GuardRenderTargets(true);
  324. View color_surface;
  325. if (using_color_fb) {
  326. const std::size_t index = regs.clear_buffers.RT;
  327. color_surface = texture_cache.GetColorBufferSurface(index);
  328. texture_cache.MarkColorBufferInUse(index);
  329. }
  330. View depth_surface;
  331. if (using_depth_fb || using_stencil_fb) {
  332. depth_surface = texture_cache.GetDepthBufferSurface();
  333. texture_cache.MarkDepthBufferInUse();
  334. }
  335. texture_cache.GuardRenderTargets(false);
  336. FramebufferCacheKey key;
  337. key.colors[0] = color_surface;
  338. key.zeta = depth_surface;
  339. state_tracker.NotifyFramebuffer();
  340. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer_cache.GetFramebuffer(key));
  341. }
  342. void RasterizerOpenGL::Clear() {
  343. const auto& gpu = system.GPU().Maxwell3D();
  344. if (!gpu.ShouldExecute()) {
  345. return;
  346. }
  347. const auto& regs = gpu.regs;
  348. bool use_color{};
  349. bool use_depth{};
  350. bool use_stencil{};
  351. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  352. regs.clear_buffers.A) {
  353. use_color = true;
  354. }
  355. if (use_color) {
  356. state_tracker.NotifyColorMask0();
  357. glColorMaski(0, regs.clear_buffers.R != 0, regs.clear_buffers.G != 0,
  358. regs.clear_buffers.B != 0, regs.clear_buffers.A != 0);
  359. // TODO(Rodrigo): Determine if clamping is used on clears
  360. SyncFragmentColorClampState();
  361. SyncFramebufferSRGB();
  362. }
  363. if (regs.clear_buffers.Z) {
  364. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  365. use_depth = true;
  366. state_tracker.NotifyDepthMask();
  367. glDepthMask(GL_TRUE);
  368. }
  369. if (regs.clear_buffers.S) {
  370. ASSERT_MSG(regs.zeta_enable, "Tried to clear stencil but buffer is not enabled!");
  371. use_stencil = true;
  372. }
  373. if (!use_color && !use_depth && !use_stencil) {
  374. // No color surface nor depth/stencil surface are enabled
  375. return;
  376. }
  377. SyncRasterizeEnable();
  378. SyncStencilTestState();
  379. if (regs.clear_flags.scissor) {
  380. SyncScissorTest();
  381. } else {
  382. state_tracker.NotifyScissor0();
  383. glDisablei(GL_SCISSOR_TEST, 0);
  384. }
  385. UNIMPLEMENTED_IF(regs.clear_flags.viewport);
  386. ConfigureClearFramebuffer(use_color, use_depth, use_stencil);
  387. if (use_color) {
  388. glClearBufferfv(GL_COLOR, 0, regs.clear_color);
  389. }
  390. if (use_depth && use_stencil) {
  391. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  392. } else if (use_depth) {
  393. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  394. } else if (use_stencil) {
  395. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  396. }
  397. ++num_queued_commands;
  398. }
  399. void RasterizerOpenGL::Draw(bool is_indexed, bool is_instanced) {
  400. MICROPROFILE_SCOPE(OpenGL_Drawing);
  401. auto& gpu = system.GPU().Maxwell3D();
  402. query_cache.UpdateCounters();
  403. SyncViewport();
  404. SyncRasterizeEnable();
  405. SyncPolygonModes();
  406. SyncColorMask();
  407. SyncFragmentColorClampState();
  408. SyncMultiSampleState();
  409. SyncDepthTestState();
  410. SyncDepthClamp();
  411. SyncStencilTestState();
  412. SyncBlendState();
  413. SyncLogicOpState();
  414. SyncCullMode();
  415. SyncPrimitiveRestart();
  416. SyncScissorTest();
  417. SyncPointState();
  418. SyncLineState();
  419. SyncPolygonOffset();
  420. SyncAlphaTest();
  421. SyncFramebufferSRGB();
  422. buffer_cache.Acquire();
  423. std::size_t buffer_size = CalculateVertexArraysSize();
  424. // Add space for index buffer
  425. if (is_indexed) {
  426. buffer_size = Common::AlignUp(buffer_size, 4) + CalculateIndexBufferSize();
  427. }
  428. // Uniform space for the 5 shader stages
  429. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) +
  430. (sizeof(GLShader::MaxwellUniformData) + device.GetUniformBufferAlignment()) *
  431. Maxwell::MaxShaderStage;
  432. // Add space for at least 18 constant buffers
  433. buffer_size += Maxwell::MaxConstBuffers *
  434. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  435. // Prepare the vertex array.
  436. buffer_cache.Map(buffer_size);
  437. // Prepare vertex array format.
  438. SetupVertexFormat();
  439. // Upload vertex and index data.
  440. SetupVertexBuffer();
  441. SetupVertexInstances();
  442. GLintptr index_buffer_offset = 0;
  443. if (is_indexed) {
  444. index_buffer_offset = SetupIndexBuffer();
  445. }
  446. // Setup emulation uniform buffer.
  447. GLShader::MaxwellUniformData ubo;
  448. ubo.SetFromRegs(gpu);
  449. const auto [buffer, offset] =
  450. buffer_cache.UploadHostMemory(&ubo, sizeof(ubo), device.GetUniformBufferAlignment());
  451. glBindBufferRange(GL_UNIFORM_BUFFER, EmulationUniformBlockBinding, buffer, offset,
  452. static_cast<GLsizeiptr>(sizeof(ubo)));
  453. // Setup shaders and their used resources.
  454. texture_cache.GuardSamplers(true);
  455. const GLenum primitive_mode = MaxwellToGL::PrimitiveTopology(gpu.regs.draw.topology);
  456. SetupShaders(primitive_mode);
  457. texture_cache.GuardSamplers(false);
  458. ConfigureFramebuffers();
  459. // Signal the buffer cache that we are not going to upload more things.
  460. buffer_cache.Unmap();
  461. program_manager.BindGraphicsPipeline();
  462. if (texture_cache.TextureBarrier()) {
  463. glTextureBarrier();
  464. }
  465. BeginTransformFeedback(primitive_mode);
  466. const GLuint base_instance = static_cast<GLuint>(gpu.regs.vb_base_instance);
  467. const GLsizei num_instances =
  468. static_cast<GLsizei>(is_instanced ? gpu.mme_draw.instance_count : 1);
  469. if (is_indexed) {
  470. const GLint base_vertex = static_cast<GLint>(gpu.regs.vb_element_base);
  471. const GLsizei num_vertices = static_cast<GLsizei>(gpu.regs.index_array.count);
  472. const GLvoid* offset = reinterpret_cast<const GLvoid*>(index_buffer_offset);
  473. const GLenum format = MaxwellToGL::IndexFormat(gpu.regs.index_array.format);
  474. if (num_instances == 1 && base_instance == 0 && base_vertex == 0) {
  475. glDrawElements(primitive_mode, num_vertices, format, offset);
  476. } else if (num_instances == 1 && base_instance == 0) {
  477. glDrawElementsBaseVertex(primitive_mode, num_vertices, format, offset, base_vertex);
  478. } else if (base_vertex == 0 && base_instance == 0) {
  479. glDrawElementsInstanced(primitive_mode, num_vertices, format, offset, num_instances);
  480. } else if (base_vertex == 0) {
  481. glDrawElementsInstancedBaseInstance(primitive_mode, num_vertices, format, offset,
  482. num_instances, base_instance);
  483. } else if (base_instance == 0) {
  484. glDrawElementsInstancedBaseVertex(primitive_mode, num_vertices, format, offset,
  485. num_instances, base_vertex);
  486. } else {
  487. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, num_vertices, format,
  488. offset, num_instances, base_vertex,
  489. base_instance);
  490. }
  491. } else {
  492. const GLint base_vertex = static_cast<GLint>(gpu.regs.vertex_buffer.first);
  493. const GLsizei num_vertices = static_cast<GLsizei>(gpu.regs.vertex_buffer.count);
  494. if (num_instances == 1 && base_instance == 0) {
  495. glDrawArrays(primitive_mode, base_vertex, num_vertices);
  496. } else if (base_instance == 0) {
  497. glDrawArraysInstanced(primitive_mode, base_vertex, num_vertices, num_instances);
  498. } else {
  499. glDrawArraysInstancedBaseInstance(primitive_mode, base_vertex, num_vertices,
  500. num_instances, base_instance);
  501. }
  502. }
  503. EndTransformFeedback();
  504. ++num_queued_commands;
  505. }
  506. void RasterizerOpenGL::DispatchCompute(GPUVAddr code_addr) {
  507. if (device.HasBrokenCompute()) {
  508. return;
  509. }
  510. buffer_cache.Acquire();
  511. auto kernel = shader_cache.GetComputeKernel(code_addr);
  512. SetupComputeTextures(kernel);
  513. SetupComputeImages(kernel);
  514. program_manager.BindComputeShader(kernel->GetHandle());
  515. const std::size_t buffer_size =
  516. Tegra::Engines::KeplerCompute::NumConstBuffers *
  517. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  518. buffer_cache.Map(buffer_size);
  519. SetupComputeConstBuffers(kernel);
  520. SetupComputeGlobalMemory(kernel);
  521. buffer_cache.Unmap();
  522. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  523. glDispatchCompute(launch_desc.grid_dim_x, launch_desc.grid_dim_y, launch_desc.grid_dim_z);
  524. ++num_queued_commands;
  525. }
  526. void RasterizerOpenGL::ResetCounter(VideoCore::QueryType type) {
  527. query_cache.ResetCounter(type);
  528. }
  529. void RasterizerOpenGL::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  530. std::optional<u64> timestamp) {
  531. query_cache.Query(gpu_addr, type, timestamp);
  532. }
  533. void RasterizerOpenGL::FlushAll() {}
  534. void RasterizerOpenGL::FlushRegion(VAddr addr, u64 size) {
  535. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  536. if (addr == 0 || size == 0) {
  537. return;
  538. }
  539. texture_cache.FlushRegion(addr, size);
  540. buffer_cache.FlushRegion(addr, size);
  541. query_cache.FlushRegion(addr, size);
  542. }
  543. void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size) {
  544. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  545. if (addr == 0 || size == 0) {
  546. return;
  547. }
  548. texture_cache.InvalidateRegion(addr, size);
  549. shader_cache.InvalidateRegion(addr, size);
  550. buffer_cache.InvalidateRegion(addr, size);
  551. query_cache.InvalidateRegion(addr, size);
  552. }
  553. void RasterizerOpenGL::OnCPUWrite(VAddr addr, u64 size) {
  554. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  555. if (!addr || !size) {
  556. return;
  557. }
  558. texture_cache.OnCPUWrite(addr, size);
  559. shader_cache.InvalidateRegion(addr, size);
  560. buffer_cache.OnCPUWrite(addr, size);
  561. }
  562. void RasterizerOpenGL::SyncGuestHost() {
  563. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  564. texture_cache.SyncGuestHost();
  565. buffer_cache.SyncGuestHost();
  566. }
  567. void RasterizerOpenGL::SignalFence(GPUVAddr addr, u32 value) {
  568. fence_manager.SignalFence(addr, value);
  569. }
  570. void RasterizerOpenGL::ReleaseFences() {
  571. fence_manager.WaitPendingFences();
  572. }
  573. void RasterizerOpenGL::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  574. if (Settings::IsGPULevelExtreme()) {
  575. FlushRegion(addr, size);
  576. }
  577. InvalidateRegion(addr, size);
  578. }
  579. void RasterizerOpenGL::FlushCommands() {
  580. // Only flush when we have commands queued to OpenGL.
  581. if (num_queued_commands == 0) {
  582. return;
  583. }
  584. num_queued_commands = 0;
  585. glFlush();
  586. }
  587. void RasterizerOpenGL::TickFrame() {
  588. // Ticking a frame means that buffers will be swapped, calling glFlush implicitly.
  589. num_queued_commands = 0;
  590. buffer_cache.TickFrame();
  591. }
  592. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  593. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  594. const Tegra::Engines::Fermi2D::Config& copy_config) {
  595. MICROPROFILE_SCOPE(OpenGL_Blits);
  596. texture_cache.DoFermiCopy(src, dst, copy_config);
  597. return true;
  598. }
  599. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  600. VAddr framebuffer_addr, u32 pixel_stride) {
  601. if (!framebuffer_addr) {
  602. return {};
  603. }
  604. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  605. const auto surface{texture_cache.TryFindFramebufferSurface(framebuffer_addr)};
  606. if (!surface) {
  607. return {};
  608. }
  609. // Verify that the cached surface is the same size and format as the requested framebuffer
  610. const auto& params{surface->GetSurfaceParams()};
  611. const auto& pixel_format{
  612. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  613. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  614. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  615. if (params.pixel_format != pixel_format) {
  616. LOG_DEBUG(Render_OpenGL, "Framebuffer pixel_format is different");
  617. }
  618. screen_info.display_texture = surface->GetTexture();
  619. screen_info.display_srgb = surface->GetSurfaceParams().srgb_conversion;
  620. return true;
  621. }
  622. void RasterizerOpenGL::SetupDrawConstBuffers(std::size_t stage_index, const Shader& shader) {
  623. MICROPROFILE_SCOPE(OpenGL_UBO);
  624. const auto& stages = system.GPU().Maxwell3D().state.shader_stages;
  625. const auto& shader_stage = stages[stage_index];
  626. u32 binding = device.GetBaseBindings(stage_index).uniform_buffer;
  627. for (const auto& entry : shader->GetEntries().const_buffers) {
  628. const auto& buffer = shader_stage.const_buffers[entry.GetIndex()];
  629. SetupConstBuffer(binding++, buffer, entry);
  630. }
  631. }
  632. void RasterizerOpenGL::SetupComputeConstBuffers(const Shader& kernel) {
  633. MICROPROFILE_SCOPE(OpenGL_UBO);
  634. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  635. u32 binding = 0;
  636. for (const auto& entry : kernel->GetEntries().const_buffers) {
  637. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  638. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  639. Tegra::Engines::ConstBufferInfo buffer;
  640. buffer.address = config.Address();
  641. buffer.size = config.size;
  642. buffer.enabled = mask[entry.GetIndex()];
  643. SetupConstBuffer(binding++, buffer, entry);
  644. }
  645. }
  646. void RasterizerOpenGL::SetupConstBuffer(u32 binding, const Tegra::Engines::ConstBufferInfo& buffer,
  647. const ConstBufferEntry& entry) {
  648. if (!buffer.enabled) {
  649. // Set values to zero to unbind buffers
  650. glBindBufferRange(GL_UNIFORM_BUFFER, binding, buffer_cache.GetEmptyBuffer(sizeof(float)), 0,
  651. sizeof(float));
  652. return;
  653. }
  654. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  655. // UBO alignment requirements.
  656. const std::size_t size = Common::AlignUp(GetConstBufferSize(buffer, entry), sizeof(GLvec4));
  657. const auto alignment = device.GetUniformBufferAlignment();
  658. const auto [cbuf, offset] = buffer_cache.UploadMemory(buffer.address, size, alignment, false,
  659. device.HasFastBufferSubData());
  660. glBindBufferRange(GL_UNIFORM_BUFFER, binding, cbuf, offset, size);
  661. }
  662. void RasterizerOpenGL::SetupDrawGlobalMemory(std::size_t stage_index, const Shader& shader) {
  663. auto& gpu{system.GPU()};
  664. auto& memory_manager{gpu.MemoryManager()};
  665. const auto cbufs{gpu.Maxwell3D().state.shader_stages[stage_index]};
  666. u32 binding = device.GetBaseBindings(stage_index).shader_storage_buffer;
  667. for (const auto& entry : shader->GetEntries().global_memory_entries) {
  668. const auto addr{cbufs.const_buffers[entry.GetCbufIndex()].address + entry.GetCbufOffset()};
  669. const auto gpu_addr{memory_manager.Read<u64>(addr)};
  670. const auto size{memory_manager.Read<u32>(addr + 8)};
  671. SetupGlobalMemory(binding++, entry, gpu_addr, size);
  672. }
  673. }
  674. void RasterizerOpenGL::SetupComputeGlobalMemory(const Shader& kernel) {
  675. auto& gpu{system.GPU()};
  676. auto& memory_manager{gpu.MemoryManager()};
  677. const auto cbufs{gpu.KeplerCompute().launch_description.const_buffer_config};
  678. u32 binding = 0;
  679. for (const auto& entry : kernel->GetEntries().global_memory_entries) {
  680. const auto addr{cbufs[entry.GetCbufIndex()].Address() + entry.GetCbufOffset()};
  681. const auto gpu_addr{memory_manager.Read<u64>(addr)};
  682. const auto size{memory_manager.Read<u32>(addr + 8)};
  683. SetupGlobalMemory(binding++, entry, gpu_addr, size);
  684. }
  685. }
  686. void RasterizerOpenGL::SetupGlobalMemory(u32 binding, const GlobalMemoryEntry& entry,
  687. GPUVAddr gpu_addr, std::size_t size) {
  688. const auto alignment{device.GetShaderStorageBufferAlignment()};
  689. const auto [ssbo, buffer_offset] =
  690. buffer_cache.UploadMemory(gpu_addr, size, alignment, entry.IsWritten());
  691. glBindBufferRange(GL_SHADER_STORAGE_BUFFER, binding, ssbo, buffer_offset,
  692. static_cast<GLsizeiptr>(size));
  693. }
  694. void RasterizerOpenGL::SetupDrawTextures(std::size_t stage_index, const Shader& shader) {
  695. MICROPROFILE_SCOPE(OpenGL_Texture);
  696. const auto& maxwell3d = system.GPU().Maxwell3D();
  697. u32 binding = device.GetBaseBindings(stage_index).sampler;
  698. for (const auto& entry : shader->GetEntries().samplers) {
  699. const auto shader_type = static_cast<ShaderType>(stage_index);
  700. for (std::size_t i = 0; i < entry.Size(); ++i) {
  701. const auto texture = GetTextureInfo(maxwell3d, entry, shader_type, i);
  702. SetupTexture(binding++, texture, entry);
  703. }
  704. }
  705. }
  706. void RasterizerOpenGL::SetupComputeTextures(const Shader& kernel) {
  707. MICROPROFILE_SCOPE(OpenGL_Texture);
  708. const auto& compute = system.GPU().KeplerCompute();
  709. u32 binding = 0;
  710. for (const auto& entry : kernel->GetEntries().samplers) {
  711. for (std::size_t i = 0; i < entry.Size(); ++i) {
  712. const auto texture = GetTextureInfo(compute, entry, ShaderType::Compute, i);
  713. SetupTexture(binding++, texture, entry);
  714. }
  715. }
  716. }
  717. void RasterizerOpenGL::SetupTexture(u32 binding, const Tegra::Texture::FullTextureInfo& texture,
  718. const SamplerEntry& entry) {
  719. const auto view = texture_cache.GetTextureSurface(texture.tic, entry);
  720. if (!view) {
  721. // Can occur when texture addr is null or its memory is unmapped/invalid
  722. glBindSampler(binding, 0);
  723. glBindTextureUnit(binding, 0);
  724. return;
  725. }
  726. glBindTextureUnit(binding, view->GetTexture());
  727. if (view->GetSurfaceParams().IsBuffer()) {
  728. return;
  729. }
  730. // Apply swizzle to textures that are not buffers.
  731. view->ApplySwizzle(texture.tic.x_source, texture.tic.y_source, texture.tic.z_source,
  732. texture.tic.w_source);
  733. glBindSampler(binding, sampler_cache.GetSampler(texture.tsc));
  734. }
  735. void RasterizerOpenGL::SetupDrawImages(std::size_t stage_index, const Shader& shader) {
  736. const auto& maxwell3d = system.GPU().Maxwell3D();
  737. u32 binding = device.GetBaseBindings(stage_index).image;
  738. for (const auto& entry : shader->GetEntries().images) {
  739. const auto shader_type = static_cast<Tegra::Engines::ShaderType>(stage_index);
  740. const auto tic = GetTextureInfo(maxwell3d, entry, shader_type).tic;
  741. SetupImage(binding++, tic, entry);
  742. }
  743. }
  744. void RasterizerOpenGL::SetupComputeImages(const Shader& shader) {
  745. const auto& compute = system.GPU().KeplerCompute();
  746. u32 binding = 0;
  747. for (const auto& entry : shader->GetEntries().images) {
  748. const auto tic = GetTextureInfo(compute, entry, Tegra::Engines::ShaderType::Compute).tic;
  749. SetupImage(binding++, tic, entry);
  750. }
  751. }
  752. void RasterizerOpenGL::SetupImage(u32 binding, const Tegra::Texture::TICEntry& tic,
  753. const ImageEntry& entry) {
  754. const auto view = texture_cache.GetImageSurface(tic, entry);
  755. if (!view) {
  756. glBindImageTexture(binding, 0, 0, GL_FALSE, 0, GL_READ_ONLY, GL_R8);
  757. return;
  758. }
  759. if (!tic.IsBuffer()) {
  760. view->ApplySwizzle(tic.x_source, tic.y_source, tic.z_source, tic.w_source);
  761. }
  762. if (entry.IsWritten()) {
  763. view->MarkAsModified(texture_cache.Tick());
  764. }
  765. glBindImageTexture(binding, view->GetTexture(), 0, GL_TRUE, 0, GL_READ_WRITE,
  766. view->GetFormat());
  767. }
  768. void RasterizerOpenGL::SyncViewport() {
  769. auto& gpu = system.GPU().Maxwell3D();
  770. auto& flags = gpu.dirty.flags;
  771. const auto& regs = gpu.regs;
  772. const bool dirty_viewport = flags[Dirty::Viewports];
  773. if (dirty_viewport || flags[Dirty::ClipControl]) {
  774. flags[Dirty::ClipControl] = false;
  775. bool flip_y = false;
  776. if (regs.viewport_transform[0].scale_y < 0.0) {
  777. flip_y = !flip_y;
  778. }
  779. if (regs.screen_y_control.y_negate != 0) {
  780. flip_y = !flip_y;
  781. }
  782. glClipControl(flip_y ? GL_UPPER_LEFT : GL_LOWER_LEFT,
  783. regs.depth_mode == Maxwell::DepthMode::ZeroToOne ? GL_ZERO_TO_ONE
  784. : GL_NEGATIVE_ONE_TO_ONE);
  785. }
  786. if (dirty_viewport) {
  787. flags[Dirty::Viewports] = false;
  788. const bool force = flags[Dirty::ViewportTransform];
  789. flags[Dirty::ViewportTransform] = false;
  790. for (std::size_t i = 0; i < Maxwell::NumViewports; ++i) {
  791. if (!force && !flags[Dirty::Viewport0 + i]) {
  792. continue;
  793. }
  794. flags[Dirty::Viewport0 + i] = false;
  795. const auto& src = regs.viewport_transform[i];
  796. const Common::Rectangle<f32> rect{src.GetRect()};
  797. glViewportIndexedf(static_cast<GLuint>(i), rect.left, rect.bottom, rect.GetWidth(),
  798. rect.GetHeight());
  799. const GLdouble reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne;
  800. const GLdouble near_depth = src.translate_z - src.scale_z * reduce_z;
  801. const GLdouble far_depth = src.translate_z + src.scale_z;
  802. glDepthRangeIndexed(static_cast<GLuint>(i), near_depth, far_depth);
  803. }
  804. }
  805. }
  806. void RasterizerOpenGL::SyncDepthClamp() {
  807. auto& gpu = system.GPU().Maxwell3D();
  808. auto& flags = gpu.dirty.flags;
  809. if (!flags[Dirty::DepthClampEnabled]) {
  810. return;
  811. }
  812. flags[Dirty::DepthClampEnabled] = false;
  813. const auto& state = gpu.regs.view_volume_clip_control;
  814. UNIMPLEMENTED_IF_MSG(state.depth_clamp_far != state.depth_clamp_near,
  815. "Unimplemented depth clamp separation!");
  816. oglEnable(GL_DEPTH_CLAMP, state.depth_clamp_far || state.depth_clamp_near);
  817. }
  818. void RasterizerOpenGL::SyncClipEnabled(u32 clip_mask) {
  819. auto& gpu = system.GPU().Maxwell3D();
  820. auto& flags = gpu.dirty.flags;
  821. if (!flags[Dirty::ClipDistances] && !flags[Dirty::Shaders]) {
  822. return;
  823. }
  824. flags[Dirty::ClipDistances] = false;
  825. clip_mask &= gpu.regs.clip_distance_enabled;
  826. if (clip_mask == last_clip_distance_mask) {
  827. return;
  828. }
  829. last_clip_distance_mask = clip_mask;
  830. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  831. oglEnable(static_cast<GLenum>(GL_CLIP_DISTANCE0 + i), (clip_mask >> i) & 1);
  832. }
  833. }
  834. void RasterizerOpenGL::SyncClipCoef() {
  835. UNIMPLEMENTED();
  836. }
  837. void RasterizerOpenGL::SyncCullMode() {
  838. auto& gpu = system.GPU().Maxwell3D();
  839. auto& flags = gpu.dirty.flags;
  840. const auto& regs = gpu.regs;
  841. if (flags[Dirty::CullTest]) {
  842. flags[Dirty::CullTest] = false;
  843. if (regs.cull_test_enabled) {
  844. glEnable(GL_CULL_FACE);
  845. glCullFace(MaxwellToGL::CullFace(regs.cull_face));
  846. } else {
  847. glDisable(GL_CULL_FACE);
  848. }
  849. }
  850. if (flags[Dirty::FrontFace]) {
  851. flags[Dirty::FrontFace] = false;
  852. glFrontFace(MaxwellToGL::FrontFace(regs.front_face));
  853. }
  854. }
  855. void RasterizerOpenGL::SyncPrimitiveRestart() {
  856. auto& gpu = system.GPU().Maxwell3D();
  857. auto& flags = gpu.dirty.flags;
  858. if (!flags[Dirty::PrimitiveRestart]) {
  859. return;
  860. }
  861. flags[Dirty::PrimitiveRestart] = false;
  862. if (gpu.regs.primitive_restart.enabled) {
  863. glEnable(GL_PRIMITIVE_RESTART);
  864. glPrimitiveRestartIndex(gpu.regs.primitive_restart.index);
  865. } else {
  866. glDisable(GL_PRIMITIVE_RESTART);
  867. }
  868. }
  869. void RasterizerOpenGL::SyncDepthTestState() {
  870. auto& gpu = system.GPU().Maxwell3D();
  871. auto& flags = gpu.dirty.flags;
  872. const auto& regs = gpu.regs;
  873. if (flags[Dirty::DepthMask]) {
  874. flags[Dirty::DepthMask] = false;
  875. glDepthMask(regs.depth_write_enabled ? GL_TRUE : GL_FALSE);
  876. }
  877. if (flags[Dirty::DepthTest]) {
  878. flags[Dirty::DepthTest] = false;
  879. if (regs.depth_test_enable) {
  880. glEnable(GL_DEPTH_TEST);
  881. glDepthFunc(MaxwellToGL::ComparisonOp(regs.depth_test_func));
  882. } else {
  883. glDisable(GL_DEPTH_TEST);
  884. }
  885. }
  886. }
  887. void RasterizerOpenGL::SyncStencilTestState() {
  888. auto& gpu = system.GPU().Maxwell3D();
  889. auto& flags = gpu.dirty.flags;
  890. if (!flags[Dirty::StencilTest]) {
  891. return;
  892. }
  893. flags[Dirty::StencilTest] = false;
  894. const auto& regs = gpu.regs;
  895. oglEnable(GL_STENCIL_TEST, regs.stencil_enable);
  896. glStencilFuncSeparate(GL_FRONT, MaxwellToGL::ComparisonOp(regs.stencil_front_func_func),
  897. regs.stencil_front_func_ref, regs.stencil_front_func_mask);
  898. glStencilOpSeparate(GL_FRONT, MaxwellToGL::StencilOp(regs.stencil_front_op_fail),
  899. MaxwellToGL::StencilOp(regs.stencil_front_op_zfail),
  900. MaxwellToGL::StencilOp(regs.stencil_front_op_zpass));
  901. glStencilMaskSeparate(GL_FRONT, regs.stencil_front_mask);
  902. if (regs.stencil_two_side_enable) {
  903. glStencilFuncSeparate(GL_BACK, MaxwellToGL::ComparisonOp(regs.stencil_back_func_func),
  904. regs.stencil_back_func_ref, regs.stencil_back_func_mask);
  905. glStencilOpSeparate(GL_BACK, MaxwellToGL::StencilOp(regs.stencil_back_op_fail),
  906. MaxwellToGL::StencilOp(regs.stencil_back_op_zfail),
  907. MaxwellToGL::StencilOp(regs.stencil_back_op_zpass));
  908. glStencilMaskSeparate(GL_BACK, regs.stencil_back_mask);
  909. } else {
  910. glStencilFuncSeparate(GL_BACK, GL_ALWAYS, 0, 0xFFFFFFFF);
  911. glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP);
  912. glStencilMaskSeparate(GL_BACK, 0xFFFFFFFF);
  913. }
  914. }
  915. void RasterizerOpenGL::SyncRasterizeEnable() {
  916. auto& gpu = system.GPU().Maxwell3D();
  917. auto& flags = gpu.dirty.flags;
  918. if (!flags[Dirty::RasterizeEnable]) {
  919. return;
  920. }
  921. flags[Dirty::RasterizeEnable] = false;
  922. oglEnable(GL_RASTERIZER_DISCARD, gpu.regs.rasterize_enable == 0);
  923. }
  924. void RasterizerOpenGL::SyncPolygonModes() {
  925. auto& gpu = system.GPU().Maxwell3D();
  926. auto& flags = gpu.dirty.flags;
  927. if (!flags[Dirty::PolygonModes]) {
  928. return;
  929. }
  930. flags[Dirty::PolygonModes] = false;
  931. if (gpu.regs.fill_rectangle) {
  932. if (!GLAD_GL_NV_fill_rectangle) {
  933. LOG_ERROR(Render_OpenGL, "GL_NV_fill_rectangle used and not supported");
  934. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  935. return;
  936. }
  937. flags[Dirty::PolygonModeFront] = true;
  938. flags[Dirty::PolygonModeBack] = true;
  939. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL_RECTANGLE_NV);
  940. return;
  941. }
  942. if (gpu.regs.polygon_mode_front == gpu.regs.polygon_mode_back) {
  943. flags[Dirty::PolygonModeFront] = false;
  944. flags[Dirty::PolygonModeBack] = false;
  945. glPolygonMode(GL_FRONT_AND_BACK, MaxwellToGL::PolygonMode(gpu.regs.polygon_mode_front));
  946. return;
  947. }
  948. if (flags[Dirty::PolygonModeFront]) {
  949. flags[Dirty::PolygonModeFront] = false;
  950. glPolygonMode(GL_FRONT, MaxwellToGL::PolygonMode(gpu.regs.polygon_mode_front));
  951. }
  952. if (flags[Dirty::PolygonModeBack]) {
  953. flags[Dirty::PolygonModeBack] = false;
  954. glPolygonMode(GL_BACK, MaxwellToGL::PolygonMode(gpu.regs.polygon_mode_back));
  955. }
  956. }
  957. void RasterizerOpenGL::SyncColorMask() {
  958. auto& gpu = system.GPU().Maxwell3D();
  959. auto& flags = gpu.dirty.flags;
  960. if (!flags[Dirty::ColorMasks]) {
  961. return;
  962. }
  963. flags[Dirty::ColorMasks] = false;
  964. const bool force = flags[Dirty::ColorMaskCommon];
  965. flags[Dirty::ColorMaskCommon] = false;
  966. const auto& regs = gpu.regs;
  967. if (regs.color_mask_common) {
  968. if (!force && !flags[Dirty::ColorMask0]) {
  969. return;
  970. }
  971. flags[Dirty::ColorMask0] = false;
  972. auto& mask = regs.color_mask[0];
  973. glColorMask(mask.R != 0, mask.B != 0, mask.G != 0, mask.A != 0);
  974. return;
  975. }
  976. // Path without color_mask_common set
  977. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  978. if (!force && !flags[Dirty::ColorMask0 + i]) {
  979. continue;
  980. }
  981. flags[Dirty::ColorMask0 + i] = false;
  982. const auto& mask = regs.color_mask[i];
  983. glColorMaski(static_cast<GLuint>(i), mask.R != 0, mask.G != 0, mask.B != 0, mask.A != 0);
  984. }
  985. }
  986. void RasterizerOpenGL::SyncMultiSampleState() {
  987. auto& gpu = system.GPU().Maxwell3D();
  988. auto& flags = gpu.dirty.flags;
  989. if (!flags[Dirty::MultisampleControl]) {
  990. return;
  991. }
  992. flags[Dirty::MultisampleControl] = false;
  993. const auto& regs = system.GPU().Maxwell3D().regs;
  994. oglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE, regs.multisample_control.alpha_to_coverage);
  995. oglEnable(GL_SAMPLE_ALPHA_TO_ONE, regs.multisample_control.alpha_to_one);
  996. }
  997. void RasterizerOpenGL::SyncFragmentColorClampState() {
  998. auto& gpu = system.GPU().Maxwell3D();
  999. auto& flags = gpu.dirty.flags;
  1000. if (!flags[Dirty::FragmentClampColor]) {
  1001. return;
  1002. }
  1003. flags[Dirty::FragmentClampColor] = false;
  1004. glClampColor(GL_CLAMP_FRAGMENT_COLOR, gpu.regs.frag_color_clamp ? GL_TRUE : GL_FALSE);
  1005. }
  1006. void RasterizerOpenGL::SyncBlendState() {
  1007. auto& gpu = system.GPU().Maxwell3D();
  1008. auto& flags = gpu.dirty.flags;
  1009. const auto& regs = gpu.regs;
  1010. if (flags[Dirty::BlendColor]) {
  1011. flags[Dirty::BlendColor] = false;
  1012. glBlendColor(regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  1013. regs.blend_color.a);
  1014. }
  1015. // TODO(Rodrigo): Revisit blending, there are several registers we are not reading
  1016. if (!flags[Dirty::BlendStates]) {
  1017. return;
  1018. }
  1019. flags[Dirty::BlendStates] = false;
  1020. if (!regs.independent_blend_enable) {
  1021. if (!regs.blend.enable[0]) {
  1022. glDisable(GL_BLEND);
  1023. return;
  1024. }
  1025. glEnable(GL_BLEND);
  1026. glBlendFuncSeparate(MaxwellToGL::BlendFunc(regs.blend.factor_source_rgb),
  1027. MaxwellToGL::BlendFunc(regs.blend.factor_dest_rgb),
  1028. MaxwellToGL::BlendFunc(regs.blend.factor_source_a),
  1029. MaxwellToGL::BlendFunc(regs.blend.factor_dest_a));
  1030. glBlendEquationSeparate(MaxwellToGL::BlendEquation(regs.blend.equation_rgb),
  1031. MaxwellToGL::BlendEquation(regs.blend.equation_a));
  1032. return;
  1033. }
  1034. const bool force = flags[Dirty::BlendIndependentEnabled];
  1035. flags[Dirty::BlendIndependentEnabled] = false;
  1036. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  1037. if (!force && !flags[Dirty::BlendState0 + i]) {
  1038. continue;
  1039. }
  1040. flags[Dirty::BlendState0 + i] = false;
  1041. if (!regs.blend.enable[i]) {
  1042. glDisablei(GL_BLEND, static_cast<GLuint>(i));
  1043. continue;
  1044. }
  1045. glEnablei(GL_BLEND, static_cast<GLuint>(i));
  1046. const auto& src = regs.independent_blend[i];
  1047. glBlendFuncSeparatei(static_cast<GLuint>(i), MaxwellToGL::BlendFunc(src.factor_source_rgb),
  1048. MaxwellToGL::BlendFunc(src.factor_dest_rgb),
  1049. MaxwellToGL::BlendFunc(src.factor_source_a),
  1050. MaxwellToGL::BlendFunc(src.factor_dest_a));
  1051. glBlendEquationSeparatei(static_cast<GLuint>(i),
  1052. MaxwellToGL::BlendEquation(src.equation_rgb),
  1053. MaxwellToGL::BlendEquation(src.equation_a));
  1054. }
  1055. }
  1056. void RasterizerOpenGL::SyncLogicOpState() {
  1057. auto& gpu = system.GPU().Maxwell3D();
  1058. auto& flags = gpu.dirty.flags;
  1059. if (!flags[Dirty::LogicOp]) {
  1060. return;
  1061. }
  1062. flags[Dirty::LogicOp] = false;
  1063. const auto& regs = gpu.regs;
  1064. if (regs.logic_op.enable) {
  1065. glEnable(GL_COLOR_LOGIC_OP);
  1066. glLogicOp(MaxwellToGL::LogicOp(regs.logic_op.operation));
  1067. } else {
  1068. glDisable(GL_COLOR_LOGIC_OP);
  1069. }
  1070. }
  1071. void RasterizerOpenGL::SyncScissorTest() {
  1072. auto& gpu = system.GPU().Maxwell3D();
  1073. auto& flags = gpu.dirty.flags;
  1074. if (!flags[Dirty::Scissors]) {
  1075. return;
  1076. }
  1077. flags[Dirty::Scissors] = false;
  1078. const auto& regs = gpu.regs;
  1079. for (std::size_t index = 0; index < Maxwell::NumViewports; ++index) {
  1080. if (!flags[Dirty::Scissor0 + index]) {
  1081. continue;
  1082. }
  1083. flags[Dirty::Scissor0 + index] = false;
  1084. const auto& src = regs.scissor_test[index];
  1085. if (src.enable) {
  1086. glEnablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  1087. glScissorIndexed(static_cast<GLuint>(index), src.min_x, src.min_y,
  1088. src.max_x - src.min_x, src.max_y - src.min_y);
  1089. } else {
  1090. glDisablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  1091. }
  1092. }
  1093. }
  1094. void RasterizerOpenGL::SyncPointState() {
  1095. auto& gpu = system.GPU().Maxwell3D();
  1096. auto& flags = gpu.dirty.flags;
  1097. if (!flags[Dirty::PointSize]) {
  1098. return;
  1099. }
  1100. flags[Dirty::PointSize] = false;
  1101. oglEnable(GL_POINT_SPRITE, gpu.regs.point_sprite_enable);
  1102. if (gpu.regs.vp_point_size.enable) {
  1103. // By definition of GL_POINT_SIZE, it only matters if GL_PROGRAM_POINT_SIZE is disabled.
  1104. glEnable(GL_PROGRAM_POINT_SIZE);
  1105. return;
  1106. }
  1107. // Limit the point size to 1 since nouveau sometimes sets a point size of 0 (and that's invalid
  1108. // in OpenGL).
  1109. glPointSize(std::max(1.0f, gpu.regs.point_size));
  1110. glDisable(GL_PROGRAM_POINT_SIZE);
  1111. }
  1112. void RasterizerOpenGL::SyncLineState() {
  1113. auto& gpu = system.GPU().Maxwell3D();
  1114. auto& flags = gpu.dirty.flags;
  1115. if (!flags[Dirty::LineWidth]) {
  1116. return;
  1117. }
  1118. flags[Dirty::LineWidth] = false;
  1119. const auto& regs = gpu.regs;
  1120. oglEnable(GL_LINE_SMOOTH, regs.line_smooth_enable);
  1121. glLineWidth(regs.line_smooth_enable ? regs.line_width_smooth : regs.line_width_aliased);
  1122. }
  1123. void RasterizerOpenGL::SyncPolygonOffset() {
  1124. auto& gpu = system.GPU().Maxwell3D();
  1125. auto& flags = gpu.dirty.flags;
  1126. if (!flags[Dirty::PolygonOffset]) {
  1127. return;
  1128. }
  1129. flags[Dirty::PolygonOffset] = false;
  1130. const auto& regs = gpu.regs;
  1131. oglEnable(GL_POLYGON_OFFSET_FILL, regs.polygon_offset_fill_enable);
  1132. oglEnable(GL_POLYGON_OFFSET_LINE, regs.polygon_offset_line_enable);
  1133. oglEnable(GL_POLYGON_OFFSET_POINT, regs.polygon_offset_point_enable);
  1134. if (regs.polygon_offset_fill_enable || regs.polygon_offset_line_enable ||
  1135. regs.polygon_offset_point_enable) {
  1136. // Hardware divides polygon offset units by two
  1137. glPolygonOffsetClamp(regs.polygon_offset_factor, regs.polygon_offset_units / 2.0f,
  1138. regs.polygon_offset_clamp);
  1139. }
  1140. }
  1141. void RasterizerOpenGL::SyncAlphaTest() {
  1142. auto& gpu = system.GPU().Maxwell3D();
  1143. auto& flags = gpu.dirty.flags;
  1144. if (!flags[Dirty::AlphaTest]) {
  1145. return;
  1146. }
  1147. flags[Dirty::AlphaTest] = false;
  1148. const auto& regs = gpu.regs;
  1149. if (regs.alpha_test_enabled && regs.rt_control.count > 1) {
  1150. LOG_WARNING(Render_OpenGL, "Alpha testing with more than one render target is not tested");
  1151. }
  1152. if (regs.alpha_test_enabled) {
  1153. glEnable(GL_ALPHA_TEST);
  1154. glAlphaFunc(MaxwellToGL::ComparisonOp(regs.alpha_test_func), regs.alpha_test_ref);
  1155. } else {
  1156. glDisable(GL_ALPHA_TEST);
  1157. }
  1158. }
  1159. void RasterizerOpenGL::SyncFramebufferSRGB() {
  1160. auto& gpu = system.GPU().Maxwell3D();
  1161. auto& flags = gpu.dirty.flags;
  1162. if (!flags[Dirty::FramebufferSRGB]) {
  1163. return;
  1164. }
  1165. flags[Dirty::FramebufferSRGB] = false;
  1166. oglEnable(GL_FRAMEBUFFER_SRGB, gpu.regs.framebuffer_srgb);
  1167. }
  1168. void RasterizerOpenGL::BeginTransformFeedback(GLenum primitive_mode) {
  1169. const auto& regs = system.GPU().Maxwell3D().regs;
  1170. if (regs.tfb_enabled == 0) {
  1171. return;
  1172. }
  1173. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationControl) ||
  1174. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationEval) ||
  1175. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::Geometry));
  1176. for (std::size_t index = 0; index < Maxwell::NumTransformFeedbackBuffers; ++index) {
  1177. const auto& binding = regs.tfb_bindings[index];
  1178. if (!binding.buffer_enable) {
  1179. if (enabled_transform_feedback_buffers[index]) {
  1180. glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, static_cast<GLuint>(index), 0, 0,
  1181. 0);
  1182. }
  1183. enabled_transform_feedback_buffers[index] = false;
  1184. continue;
  1185. }
  1186. enabled_transform_feedback_buffers[index] = true;
  1187. auto& tfb_buffer = transform_feedback_buffers[index];
  1188. tfb_buffer.Create();
  1189. const GLuint handle = tfb_buffer.handle;
  1190. const std::size_t size = binding.buffer_size;
  1191. glNamedBufferData(handle, static_cast<GLsizeiptr>(size), nullptr, GL_STREAM_COPY);
  1192. glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, static_cast<GLuint>(index), handle, 0,
  1193. static_cast<GLsizeiptr>(size));
  1194. }
  1195. glBeginTransformFeedback(GL_POINTS);
  1196. }
  1197. void RasterizerOpenGL::EndTransformFeedback() {
  1198. const auto& regs = system.GPU().Maxwell3D().regs;
  1199. if (regs.tfb_enabled == 0) {
  1200. return;
  1201. }
  1202. glEndTransformFeedback();
  1203. for (std::size_t index = 0; index < Maxwell::NumTransformFeedbackBuffers; ++index) {
  1204. const auto& binding = regs.tfb_bindings[index];
  1205. if (!binding.buffer_enable) {
  1206. continue;
  1207. }
  1208. UNIMPLEMENTED_IF(binding.buffer_offset != 0);
  1209. const GLuint handle = transform_feedback_buffers[index].handle;
  1210. const GPUVAddr gpu_addr = binding.Address();
  1211. const std::size_t size = binding.buffer_size;
  1212. const auto [dest_buffer, offset] = buffer_cache.UploadMemory(gpu_addr, size, 4, true);
  1213. glCopyNamedBufferSubData(handle, dest_buffer, 0, offset, static_cast<GLsizeiptr>(size));
  1214. }
  1215. }
  1216. } // namespace OpenGL