gl_rasterizer.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  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} {
  91. CheckExtensions();
  92. }
  93. RasterizerOpenGL::~RasterizerOpenGL() {}
  94. void RasterizerOpenGL::CheckExtensions() {
  95. if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
  96. LOG_WARNING(
  97. Render_OpenGL,
  98. "Anisotropic filter is not supported! This can cause graphical issues in some games.");
  99. }
  100. }
  101. void RasterizerOpenGL::SetupVertexFormat() {
  102. auto& gpu = system.GPU().Maxwell3D();
  103. auto& flags = gpu.dirty.flags;
  104. if (!flags[Dirty::VertexFormats]) {
  105. return;
  106. }
  107. flags[Dirty::VertexFormats] = false;
  108. MICROPROFILE_SCOPE(OpenGL_VAO);
  109. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL. Enables
  110. // the first 16 vertex attributes always, as we don't know which ones are actually used until
  111. // shader time. Note, Tegra technically supports 32, but we're capping this to 16 for now to
  112. // avoid OpenGL errors.
  113. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  114. // assume every shader uses them all.
  115. for (std::size_t index = 0; index < NumSupportedVertexAttributes; ++index) {
  116. if (!flags[Dirty::VertexFormat0 + index]) {
  117. continue;
  118. }
  119. flags[Dirty::VertexFormat0 + index] = false;
  120. const auto attrib = gpu.regs.vertex_attrib_format[index];
  121. const auto gl_index = static_cast<GLuint>(index);
  122. // Ignore invalid attributes.
  123. if (!attrib.IsValid()) {
  124. glDisableVertexAttribArray(gl_index);
  125. continue;
  126. }
  127. glEnableVertexAttribArray(gl_index);
  128. if (attrib.type == Maxwell::VertexAttribute::Type::SignedInt ||
  129. attrib.type == Maxwell::VertexAttribute::Type::UnsignedInt) {
  130. glVertexAttribIFormat(gl_index, attrib.ComponentCount(),
  131. MaxwellToGL::VertexType(attrib), attrib.offset);
  132. } else {
  133. glVertexAttribFormat(gl_index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  134. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  135. }
  136. glVertexAttribBinding(gl_index, attrib.buffer);
  137. }
  138. }
  139. void RasterizerOpenGL::SetupVertexBuffer() {
  140. auto& gpu = system.GPU().Maxwell3D();
  141. auto& flags = gpu.dirty.flags;
  142. if (!flags[Dirty::VertexBuffers]) {
  143. return;
  144. }
  145. flags[Dirty::VertexBuffers] = false;
  146. MICROPROFILE_SCOPE(OpenGL_VB);
  147. // Upload all guest vertex arrays sequentially to our buffer
  148. const auto& regs = gpu.regs;
  149. for (std::size_t index = 0; index < Maxwell::NumVertexArrays; ++index) {
  150. if (!flags[Dirty::VertexBuffer0 + index]) {
  151. continue;
  152. }
  153. flags[Dirty::VertexBuffer0 + index] = false;
  154. const auto& vertex_array = regs.vertex_array[index];
  155. if (!vertex_array.IsEnabled()) {
  156. continue;
  157. }
  158. const GPUVAddr start = vertex_array.StartAddress();
  159. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  160. ASSERT(end > start);
  161. const u64 size = end - start + 1;
  162. const auto [vertex_buffer, vertex_buffer_offset] = buffer_cache.UploadMemory(start, size);
  163. // Bind the vertex array to the buffer at the current offset.
  164. vertex_array_pushbuffer.SetVertexBuffer(static_cast<GLuint>(index), vertex_buffer,
  165. vertex_buffer_offset, 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. vertex_array_pushbuffer.SetIndexBuffer(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(true);
  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, true)};
  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, true);
  328. texture_cache.MarkColorBufferInUse(index);
  329. }
  330. View depth_surface;
  331. if (using_depth_fb || using_stencil_fb) {
  332. depth_surface = texture_cache.GetDepthBufferSurface(true);
  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. SyncPolygonOffset();
  419. SyncAlphaTest();
  420. SyncFramebufferSRGB();
  421. buffer_cache.Acquire();
  422. std::size_t buffer_size = CalculateVertexArraysSize();
  423. // Add space for index buffer
  424. if (is_indexed) {
  425. buffer_size = Common::AlignUp(buffer_size, 4) + CalculateIndexBufferSize();
  426. }
  427. // Uniform space for the 5 shader stages
  428. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) +
  429. (sizeof(GLShader::MaxwellUniformData) + device.GetUniformBufferAlignment()) *
  430. Maxwell::MaxShaderStage;
  431. // Add space for at least 18 constant buffers
  432. buffer_size += Maxwell::MaxConstBuffers *
  433. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  434. // Prepare the vertex array.
  435. buffer_cache.Map(buffer_size);
  436. // Prepare vertex array format.
  437. SetupVertexFormat();
  438. vertex_array_pushbuffer.Setup();
  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. // Prepare packed bindings.
  447. bind_ubo_pushbuffer.Setup();
  448. bind_ssbo_pushbuffer.Setup();
  449. // Setup emulation uniform buffer.
  450. GLShader::MaxwellUniformData ubo;
  451. ubo.SetFromRegs(gpu);
  452. const auto [buffer, offset] =
  453. buffer_cache.UploadHostMemory(&ubo, sizeof(ubo), device.GetUniformBufferAlignment());
  454. bind_ubo_pushbuffer.Push(EmulationUniformBlockBinding, buffer, offset,
  455. static_cast<GLsizeiptr>(sizeof(ubo)));
  456. // Setup shaders and their used resources.
  457. texture_cache.GuardSamplers(true);
  458. const GLenum primitive_mode = MaxwellToGL::PrimitiveTopology(gpu.regs.draw.topology);
  459. SetupShaders(primitive_mode);
  460. texture_cache.GuardSamplers(false);
  461. ConfigureFramebuffers();
  462. // Signal the buffer cache that we are not going to upload more things.
  463. buffer_cache.Unmap();
  464. // Now that we are no longer uploading data, we can safely bind the buffers to OpenGL.
  465. vertex_array_pushbuffer.Bind();
  466. bind_ubo_pushbuffer.Bind();
  467. bind_ssbo_pushbuffer.Bind();
  468. program_manager.BindGraphicsPipeline();
  469. if (texture_cache.TextureBarrier()) {
  470. glTextureBarrier();
  471. }
  472. BeginTransformFeedback(primitive_mode);
  473. const GLuint base_instance = static_cast<GLuint>(gpu.regs.vb_base_instance);
  474. const GLsizei num_instances =
  475. static_cast<GLsizei>(is_instanced ? gpu.mme_draw.instance_count : 1);
  476. if (is_indexed) {
  477. const GLint base_vertex = static_cast<GLint>(gpu.regs.vb_element_base);
  478. const GLsizei num_vertices = static_cast<GLsizei>(gpu.regs.index_array.count);
  479. const GLvoid* offset = reinterpret_cast<const GLvoid*>(index_buffer_offset);
  480. const GLenum format = MaxwellToGL::IndexFormat(gpu.regs.index_array.format);
  481. if (num_instances == 1 && base_instance == 0 && base_vertex == 0) {
  482. glDrawElements(primitive_mode, num_vertices, format, offset);
  483. } else if (num_instances == 1 && base_instance == 0) {
  484. glDrawElementsBaseVertex(primitive_mode, num_vertices, format, offset, base_vertex);
  485. } else if (base_vertex == 0 && base_instance == 0) {
  486. glDrawElementsInstanced(primitive_mode, num_vertices, format, offset, num_instances);
  487. } else if (base_vertex == 0) {
  488. glDrawElementsInstancedBaseInstance(primitive_mode, num_vertices, format, offset,
  489. num_instances, base_instance);
  490. } else if (base_instance == 0) {
  491. glDrawElementsInstancedBaseVertex(primitive_mode, num_vertices, format, offset,
  492. num_instances, base_vertex);
  493. } else {
  494. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, num_vertices, format,
  495. offset, num_instances, base_vertex,
  496. base_instance);
  497. }
  498. } else {
  499. const GLint base_vertex = static_cast<GLint>(gpu.regs.vertex_buffer.first);
  500. const GLsizei num_vertices = static_cast<GLsizei>(gpu.regs.vertex_buffer.count);
  501. if (num_instances == 1 && base_instance == 0) {
  502. glDrawArrays(primitive_mode, base_vertex, num_vertices);
  503. } else if (base_instance == 0) {
  504. glDrawArraysInstanced(primitive_mode, base_vertex, num_vertices, num_instances);
  505. } else {
  506. glDrawArraysInstancedBaseInstance(primitive_mode, base_vertex, num_vertices,
  507. num_instances, base_instance);
  508. }
  509. }
  510. EndTransformFeedback();
  511. ++num_queued_commands;
  512. }
  513. void RasterizerOpenGL::DispatchCompute(GPUVAddr code_addr) {
  514. if (device.HasBrokenCompute()) {
  515. return;
  516. }
  517. buffer_cache.Acquire();
  518. auto kernel = shader_cache.GetComputeKernel(code_addr);
  519. SetupComputeTextures(kernel);
  520. SetupComputeImages(kernel);
  521. program_manager.BindComputeShader(kernel->GetHandle());
  522. const std::size_t buffer_size =
  523. Tegra::Engines::KeplerCompute::NumConstBuffers *
  524. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  525. buffer_cache.Map(buffer_size);
  526. bind_ubo_pushbuffer.Setup();
  527. bind_ssbo_pushbuffer.Setup();
  528. SetupComputeConstBuffers(kernel);
  529. SetupComputeGlobalMemory(kernel);
  530. buffer_cache.Unmap();
  531. bind_ubo_pushbuffer.Bind();
  532. bind_ssbo_pushbuffer.Bind();
  533. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  534. glDispatchCompute(launch_desc.grid_dim_x, launch_desc.grid_dim_y, launch_desc.grid_dim_z);
  535. ++num_queued_commands;
  536. }
  537. void RasterizerOpenGL::ResetCounter(VideoCore::QueryType type) {
  538. query_cache.ResetCounter(type);
  539. }
  540. void RasterizerOpenGL::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  541. std::optional<u64> timestamp) {
  542. query_cache.Query(gpu_addr, type, timestamp);
  543. }
  544. void RasterizerOpenGL::FlushAll() {}
  545. void RasterizerOpenGL::FlushRegion(VAddr addr, u64 size) {
  546. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  547. if (!addr || !size) {
  548. return;
  549. }
  550. texture_cache.FlushRegion(addr, size);
  551. buffer_cache.FlushRegion(addr, size);
  552. query_cache.FlushRegion(addr, size);
  553. }
  554. void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size) {
  555. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  556. if (!addr || !size) {
  557. return;
  558. }
  559. CacheAddr cache_addr = ToCacheAddr(system.Memory().GetPointer(addr));
  560. texture_cache.InvalidateRegion(addr, size);
  561. shader_cache.InvalidateRegion(cache_addr, size);
  562. buffer_cache.InvalidateRegion(addr, size);
  563. query_cache.InvalidateRegion(addr, size);
  564. }
  565. void RasterizerOpenGL::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  566. if (Settings::values.use_accurate_gpu_emulation) {
  567. FlushRegion(addr, size);
  568. }
  569. InvalidateRegion(addr, size);
  570. }
  571. void RasterizerOpenGL::FlushCommands() {
  572. // Only flush when we have commands queued to OpenGL.
  573. if (num_queued_commands == 0) {
  574. return;
  575. }
  576. num_queued_commands = 0;
  577. glFlush();
  578. }
  579. void RasterizerOpenGL::TickFrame() {
  580. // Ticking a frame means that buffers will be swapped, calling glFlush implicitly.
  581. num_queued_commands = 0;
  582. buffer_cache.TickFrame();
  583. }
  584. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  585. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  586. const Tegra::Engines::Fermi2D::Config& copy_config) {
  587. MICROPROFILE_SCOPE(OpenGL_Blits);
  588. texture_cache.DoFermiCopy(src, dst, copy_config);
  589. return true;
  590. }
  591. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  592. VAddr framebuffer_addr, u32 pixel_stride) {
  593. if (!framebuffer_addr) {
  594. return {};
  595. }
  596. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  597. const auto surface{texture_cache.TryFindFramebufferSurface(framebuffer_addr)};
  598. if (!surface) {
  599. return {};
  600. }
  601. // Verify that the cached surface is the same size and format as the requested framebuffer
  602. const auto& params{surface->GetSurfaceParams()};
  603. const auto& pixel_format{
  604. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  605. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  606. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  607. if (params.pixel_format != pixel_format) {
  608. LOG_DEBUG(Render_OpenGL, "Framebuffer pixel_format is different");
  609. }
  610. screen_info.display_texture = surface->GetTexture();
  611. screen_info.display_srgb = surface->GetSurfaceParams().srgb_conversion;
  612. return true;
  613. }
  614. void RasterizerOpenGL::SetupDrawConstBuffers(std::size_t stage_index, const Shader& shader) {
  615. MICROPROFILE_SCOPE(OpenGL_UBO);
  616. const auto& stages = system.GPU().Maxwell3D().state.shader_stages;
  617. const auto& shader_stage = stages[stage_index];
  618. u32 binding = device.GetBaseBindings(stage_index).uniform_buffer;
  619. for (const auto& entry : shader->GetEntries().const_buffers) {
  620. const auto& buffer = shader_stage.const_buffers[entry.GetIndex()];
  621. SetupConstBuffer(binding++, buffer, entry);
  622. }
  623. }
  624. void RasterizerOpenGL::SetupComputeConstBuffers(const Shader& kernel) {
  625. MICROPROFILE_SCOPE(OpenGL_UBO);
  626. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  627. u32 binding = 0;
  628. for (const auto& entry : kernel->GetEntries().const_buffers) {
  629. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  630. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  631. Tegra::Engines::ConstBufferInfo buffer;
  632. buffer.address = config.Address();
  633. buffer.size = config.size;
  634. buffer.enabled = mask[entry.GetIndex()];
  635. SetupConstBuffer(binding++, buffer, entry);
  636. }
  637. }
  638. void RasterizerOpenGL::SetupConstBuffer(u32 binding, const Tegra::Engines::ConstBufferInfo& buffer,
  639. const ConstBufferEntry& entry) {
  640. if (!buffer.enabled) {
  641. // Set values to zero to unbind buffers
  642. bind_ubo_pushbuffer.Push(binding, buffer_cache.GetEmptyBuffer(sizeof(float)), 0,
  643. sizeof(float));
  644. return;
  645. }
  646. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  647. // UBO alignment requirements.
  648. const std::size_t size = Common::AlignUp(GetConstBufferSize(buffer, entry), sizeof(GLvec4));
  649. const auto alignment = device.GetUniformBufferAlignment();
  650. const auto [cbuf, offset] = buffer_cache.UploadMemory(buffer.address, size, alignment, false,
  651. device.HasFastBufferSubData());
  652. bind_ubo_pushbuffer.Push(binding, cbuf, offset, size);
  653. }
  654. void RasterizerOpenGL::SetupDrawGlobalMemory(std::size_t stage_index, const Shader& shader) {
  655. auto& gpu{system.GPU()};
  656. auto& memory_manager{gpu.MemoryManager()};
  657. const auto cbufs{gpu.Maxwell3D().state.shader_stages[stage_index]};
  658. u32 binding = device.GetBaseBindings(stage_index).shader_storage_buffer;
  659. for (const auto& entry : shader->GetEntries().global_memory_entries) {
  660. const auto addr{cbufs.const_buffers[entry.GetCbufIndex()].address + entry.GetCbufOffset()};
  661. const auto gpu_addr{memory_manager.Read<u64>(addr)};
  662. const auto size{memory_manager.Read<u32>(addr + 8)};
  663. SetupGlobalMemory(binding++, entry, gpu_addr, size);
  664. }
  665. }
  666. void RasterizerOpenGL::SetupComputeGlobalMemory(const Shader& kernel) {
  667. auto& gpu{system.GPU()};
  668. auto& memory_manager{gpu.MemoryManager()};
  669. const auto cbufs{gpu.KeplerCompute().launch_description.const_buffer_config};
  670. u32 binding = 0;
  671. for (const auto& entry : kernel->GetEntries().global_memory_entries) {
  672. const auto addr{cbufs[entry.GetCbufIndex()].Address() + entry.GetCbufOffset()};
  673. const auto gpu_addr{memory_manager.Read<u64>(addr)};
  674. const auto size{memory_manager.Read<u32>(addr + 8)};
  675. SetupGlobalMemory(binding++, entry, gpu_addr, size);
  676. }
  677. }
  678. void RasterizerOpenGL::SetupGlobalMemory(u32 binding, const GlobalMemoryEntry& entry,
  679. GPUVAddr gpu_addr, std::size_t size) {
  680. const auto alignment{device.GetShaderStorageBufferAlignment()};
  681. const auto [ssbo, buffer_offset] =
  682. buffer_cache.UploadMemory(gpu_addr, size, alignment, entry.IsWritten());
  683. bind_ssbo_pushbuffer.Push(binding, ssbo, buffer_offset, static_cast<GLsizeiptr>(size));
  684. }
  685. void RasterizerOpenGL::SetupDrawTextures(std::size_t stage_index, const Shader& shader) {
  686. MICROPROFILE_SCOPE(OpenGL_Texture);
  687. const auto& maxwell3d = system.GPU().Maxwell3D();
  688. u32 binding = device.GetBaseBindings(stage_index).sampler;
  689. for (const auto& entry : shader->GetEntries().samplers) {
  690. const auto shader_type = static_cast<ShaderType>(stage_index);
  691. for (std::size_t i = 0; i < entry.Size(); ++i) {
  692. const auto texture = GetTextureInfo(maxwell3d, entry, shader_type, i);
  693. SetupTexture(binding++, texture, entry);
  694. }
  695. }
  696. }
  697. void RasterizerOpenGL::SetupComputeTextures(const Shader& kernel) {
  698. MICROPROFILE_SCOPE(OpenGL_Texture);
  699. const auto& compute = system.GPU().KeplerCompute();
  700. u32 binding = 0;
  701. for (const auto& entry : kernel->GetEntries().samplers) {
  702. for (std::size_t i = 0; i < entry.Size(); ++i) {
  703. const auto texture = GetTextureInfo(compute, entry, ShaderType::Compute, i);
  704. SetupTexture(binding++, texture, entry);
  705. }
  706. }
  707. }
  708. void RasterizerOpenGL::SetupTexture(u32 binding, const Tegra::Texture::FullTextureInfo& texture,
  709. const SamplerEntry& entry) {
  710. const auto view = texture_cache.GetTextureSurface(texture.tic, entry);
  711. if (!view) {
  712. // Can occur when texture addr is null or its memory is unmapped/invalid
  713. glBindSampler(binding, 0);
  714. glBindTextureUnit(binding, 0);
  715. return;
  716. }
  717. glBindTextureUnit(binding, view->GetTexture());
  718. if (view->GetSurfaceParams().IsBuffer()) {
  719. return;
  720. }
  721. // Apply swizzle to textures that are not buffers.
  722. view->ApplySwizzle(texture.tic.x_source, texture.tic.y_source, texture.tic.z_source,
  723. texture.tic.w_source);
  724. glBindSampler(binding, sampler_cache.GetSampler(texture.tsc));
  725. }
  726. void RasterizerOpenGL::SetupDrawImages(std::size_t stage_index, const Shader& shader) {
  727. const auto& maxwell3d = system.GPU().Maxwell3D();
  728. u32 binding = device.GetBaseBindings(stage_index).image;
  729. for (const auto& entry : shader->GetEntries().images) {
  730. const auto shader_type = static_cast<Tegra::Engines::ShaderType>(stage_index);
  731. const auto tic = GetTextureInfo(maxwell3d, entry, shader_type).tic;
  732. SetupImage(binding++, tic, entry);
  733. }
  734. }
  735. void RasterizerOpenGL::SetupComputeImages(const Shader& shader) {
  736. const auto& compute = system.GPU().KeplerCompute();
  737. u32 binding = 0;
  738. for (const auto& entry : shader->GetEntries().images) {
  739. const auto tic = GetTextureInfo(compute, entry, Tegra::Engines::ShaderType::Compute).tic;
  740. SetupImage(binding++, tic, entry);
  741. }
  742. }
  743. void RasterizerOpenGL::SetupImage(u32 binding, const Tegra::Texture::TICEntry& tic,
  744. const ImageEntry& entry) {
  745. const auto view = texture_cache.GetImageSurface(tic, entry);
  746. if (!view) {
  747. glBindImageTexture(binding, 0, 0, GL_FALSE, 0, GL_READ_ONLY, GL_R8);
  748. return;
  749. }
  750. if (!tic.IsBuffer()) {
  751. view->ApplySwizzle(tic.x_source, tic.y_source, tic.z_source, tic.w_source);
  752. }
  753. if (entry.IsWritten()) {
  754. view->MarkAsModified(texture_cache.Tick());
  755. }
  756. glBindImageTexture(binding, view->GetTexture(), 0, GL_TRUE, 0, GL_READ_WRITE,
  757. view->GetFormat());
  758. }
  759. void RasterizerOpenGL::SyncViewport() {
  760. auto& gpu = system.GPU().Maxwell3D();
  761. auto& flags = gpu.dirty.flags;
  762. const auto& regs = gpu.regs;
  763. const bool dirty_viewport = flags[Dirty::Viewports];
  764. if (dirty_viewport || flags[Dirty::ClipControl]) {
  765. flags[Dirty::ClipControl] = false;
  766. bool flip_y = false;
  767. if (regs.viewport_transform[0].scale_y < 0.0) {
  768. flip_y = !flip_y;
  769. }
  770. if (regs.screen_y_control.y_negate != 0) {
  771. flip_y = !flip_y;
  772. }
  773. glClipControl(flip_y ? GL_UPPER_LEFT : GL_LOWER_LEFT,
  774. regs.depth_mode == Maxwell::DepthMode::ZeroToOne ? GL_ZERO_TO_ONE
  775. : GL_NEGATIVE_ONE_TO_ONE);
  776. }
  777. if (dirty_viewport) {
  778. flags[Dirty::Viewports] = false;
  779. const bool force = flags[Dirty::ViewportTransform];
  780. flags[Dirty::ViewportTransform] = false;
  781. for (std::size_t i = 0; i < Maxwell::NumViewports; ++i) {
  782. if (!force && !flags[Dirty::Viewport0 + i]) {
  783. continue;
  784. }
  785. flags[Dirty::Viewport0 + i] = false;
  786. const auto& src = regs.viewport_transform[i];
  787. const Common::Rectangle<f32> rect{src.GetRect()};
  788. glViewportIndexedf(static_cast<GLuint>(i), rect.left, rect.bottom, rect.GetWidth(),
  789. rect.GetHeight());
  790. const GLdouble reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne;
  791. const GLdouble near_depth = src.translate_z - src.scale_z * reduce_z;
  792. const GLdouble far_depth = src.translate_z + src.scale_z;
  793. glDepthRangeIndexed(static_cast<GLuint>(i), near_depth, far_depth);
  794. }
  795. }
  796. }
  797. void RasterizerOpenGL::SyncDepthClamp() {
  798. auto& gpu = system.GPU().Maxwell3D();
  799. auto& flags = gpu.dirty.flags;
  800. if (!flags[Dirty::DepthClampEnabled]) {
  801. return;
  802. }
  803. flags[Dirty::DepthClampEnabled] = false;
  804. const auto& state = gpu.regs.view_volume_clip_control;
  805. UNIMPLEMENTED_IF_MSG(state.depth_clamp_far != state.depth_clamp_near,
  806. "Unimplemented depth clamp separation!");
  807. oglEnable(GL_DEPTH_CLAMP, state.depth_clamp_far || state.depth_clamp_near);
  808. }
  809. void RasterizerOpenGL::SyncClipEnabled(u32 clip_mask) {
  810. auto& gpu = system.GPU().Maxwell3D();
  811. auto& flags = gpu.dirty.flags;
  812. if (!flags[Dirty::ClipDistances] && !flags[Dirty::Shaders]) {
  813. return;
  814. }
  815. flags[Dirty::ClipDistances] = false;
  816. clip_mask &= gpu.regs.clip_distance_enabled;
  817. if (clip_mask == last_clip_distance_mask) {
  818. return;
  819. }
  820. last_clip_distance_mask = clip_mask;
  821. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  822. oglEnable(static_cast<GLenum>(GL_CLIP_DISTANCE0 + i), (clip_mask >> i) & 1);
  823. }
  824. }
  825. void RasterizerOpenGL::SyncClipCoef() {
  826. UNIMPLEMENTED();
  827. }
  828. void RasterizerOpenGL::SyncCullMode() {
  829. auto& gpu = system.GPU().Maxwell3D();
  830. auto& flags = gpu.dirty.flags;
  831. const auto& regs = gpu.regs;
  832. if (flags[Dirty::CullTest]) {
  833. flags[Dirty::CullTest] = false;
  834. if (regs.cull_test_enabled) {
  835. glEnable(GL_CULL_FACE);
  836. glCullFace(MaxwellToGL::CullFace(regs.cull_face));
  837. } else {
  838. glDisable(GL_CULL_FACE);
  839. }
  840. }
  841. if (flags[Dirty::FrontFace]) {
  842. flags[Dirty::FrontFace] = false;
  843. glFrontFace(MaxwellToGL::FrontFace(regs.front_face));
  844. }
  845. }
  846. void RasterizerOpenGL::SyncPrimitiveRestart() {
  847. auto& gpu = system.GPU().Maxwell3D();
  848. auto& flags = gpu.dirty.flags;
  849. if (!flags[Dirty::PrimitiveRestart]) {
  850. return;
  851. }
  852. flags[Dirty::PrimitiveRestart] = false;
  853. if (gpu.regs.primitive_restart.enabled) {
  854. glEnable(GL_PRIMITIVE_RESTART);
  855. glPrimitiveRestartIndex(gpu.regs.primitive_restart.index);
  856. } else {
  857. glDisable(GL_PRIMITIVE_RESTART);
  858. }
  859. }
  860. void RasterizerOpenGL::SyncDepthTestState() {
  861. auto& gpu = system.GPU().Maxwell3D();
  862. auto& flags = gpu.dirty.flags;
  863. const auto& regs = gpu.regs;
  864. if (flags[Dirty::DepthMask]) {
  865. flags[Dirty::DepthMask] = false;
  866. glDepthMask(regs.depth_write_enabled ? GL_TRUE : GL_FALSE);
  867. }
  868. if (flags[Dirty::DepthTest]) {
  869. flags[Dirty::DepthTest] = false;
  870. if (regs.depth_test_enable) {
  871. glEnable(GL_DEPTH_TEST);
  872. glDepthFunc(MaxwellToGL::ComparisonOp(regs.depth_test_func));
  873. } else {
  874. glDisable(GL_DEPTH_TEST);
  875. }
  876. }
  877. }
  878. void RasterizerOpenGL::SyncStencilTestState() {
  879. auto& gpu = system.GPU().Maxwell3D();
  880. auto& flags = gpu.dirty.flags;
  881. if (!flags[Dirty::StencilTest]) {
  882. return;
  883. }
  884. flags[Dirty::StencilTest] = false;
  885. const auto& regs = gpu.regs;
  886. oglEnable(GL_STENCIL_TEST, regs.stencil_enable);
  887. glStencilFuncSeparate(GL_FRONT, MaxwellToGL::ComparisonOp(regs.stencil_front_func_func),
  888. regs.stencil_front_func_ref, regs.stencil_front_func_mask);
  889. glStencilOpSeparate(GL_FRONT, MaxwellToGL::StencilOp(regs.stencil_front_op_fail),
  890. MaxwellToGL::StencilOp(regs.stencil_front_op_zfail),
  891. MaxwellToGL::StencilOp(regs.stencil_front_op_zpass));
  892. glStencilMaskSeparate(GL_FRONT, regs.stencil_front_mask);
  893. if (regs.stencil_two_side_enable) {
  894. glStencilFuncSeparate(GL_BACK, MaxwellToGL::ComparisonOp(regs.stencil_back_func_func),
  895. regs.stencil_back_func_ref, regs.stencil_back_func_mask);
  896. glStencilOpSeparate(GL_BACK, MaxwellToGL::StencilOp(regs.stencil_back_op_fail),
  897. MaxwellToGL::StencilOp(regs.stencil_back_op_zfail),
  898. MaxwellToGL::StencilOp(regs.stencil_back_op_zpass));
  899. glStencilMaskSeparate(GL_BACK, regs.stencil_back_mask);
  900. } else {
  901. glStencilFuncSeparate(GL_BACK, GL_ALWAYS, 0, 0xFFFFFFFF);
  902. glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP);
  903. glStencilMaskSeparate(GL_BACK, 0xFFFFFFFF);
  904. }
  905. }
  906. void RasterizerOpenGL::SyncRasterizeEnable() {
  907. auto& gpu = system.GPU().Maxwell3D();
  908. auto& flags = gpu.dirty.flags;
  909. if (!flags[Dirty::RasterizeEnable]) {
  910. return;
  911. }
  912. flags[Dirty::RasterizeEnable] = false;
  913. oglEnable(GL_RASTERIZER_DISCARD, gpu.regs.rasterize_enable == 0);
  914. }
  915. void RasterizerOpenGL::SyncPolygonModes() {
  916. auto& gpu = system.GPU().Maxwell3D();
  917. auto& flags = gpu.dirty.flags;
  918. if (!flags[Dirty::PolygonModes]) {
  919. return;
  920. }
  921. flags[Dirty::PolygonModes] = false;
  922. if (gpu.regs.fill_rectangle) {
  923. if (!GLAD_GL_NV_fill_rectangle) {
  924. LOG_ERROR(Render_OpenGL, "GL_NV_fill_rectangle used and not supported");
  925. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  926. return;
  927. }
  928. flags[Dirty::PolygonModeFront] = true;
  929. flags[Dirty::PolygonModeBack] = true;
  930. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL_RECTANGLE_NV);
  931. return;
  932. }
  933. if (gpu.regs.polygon_mode_front == gpu.regs.polygon_mode_back) {
  934. flags[Dirty::PolygonModeFront] = false;
  935. flags[Dirty::PolygonModeBack] = false;
  936. glPolygonMode(GL_FRONT_AND_BACK, MaxwellToGL::PolygonMode(gpu.regs.polygon_mode_front));
  937. return;
  938. }
  939. if (flags[Dirty::PolygonModeFront]) {
  940. flags[Dirty::PolygonModeFront] = false;
  941. glPolygonMode(GL_FRONT, MaxwellToGL::PolygonMode(gpu.regs.polygon_mode_front));
  942. }
  943. if (flags[Dirty::PolygonModeBack]) {
  944. flags[Dirty::PolygonModeBack] = false;
  945. glPolygonMode(GL_BACK, MaxwellToGL::PolygonMode(gpu.regs.polygon_mode_back));
  946. }
  947. }
  948. void RasterizerOpenGL::SyncColorMask() {
  949. auto& gpu = system.GPU().Maxwell3D();
  950. auto& flags = gpu.dirty.flags;
  951. if (!flags[Dirty::ColorMasks]) {
  952. return;
  953. }
  954. flags[Dirty::ColorMasks] = false;
  955. const bool force = flags[Dirty::ColorMaskCommon];
  956. flags[Dirty::ColorMaskCommon] = false;
  957. const auto& regs = gpu.regs;
  958. if (regs.color_mask_common) {
  959. if (!force && !flags[Dirty::ColorMask0]) {
  960. return;
  961. }
  962. flags[Dirty::ColorMask0] = false;
  963. auto& mask = regs.color_mask[0];
  964. glColorMask(mask.R != 0, mask.B != 0, mask.G != 0, mask.A != 0);
  965. return;
  966. }
  967. // Path without color_mask_common set
  968. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  969. if (!force && !flags[Dirty::ColorMask0 + i]) {
  970. continue;
  971. }
  972. flags[Dirty::ColorMask0 + i] = false;
  973. const auto& mask = regs.color_mask[i];
  974. glColorMaski(static_cast<GLuint>(i), mask.R != 0, mask.G != 0, mask.B != 0, mask.A != 0);
  975. }
  976. }
  977. void RasterizerOpenGL::SyncMultiSampleState() {
  978. auto& gpu = system.GPU().Maxwell3D();
  979. auto& flags = gpu.dirty.flags;
  980. if (!flags[Dirty::MultisampleControl]) {
  981. return;
  982. }
  983. flags[Dirty::MultisampleControl] = false;
  984. const auto& regs = system.GPU().Maxwell3D().regs;
  985. oglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE, regs.multisample_control.alpha_to_coverage);
  986. oglEnable(GL_SAMPLE_ALPHA_TO_ONE, regs.multisample_control.alpha_to_one);
  987. }
  988. void RasterizerOpenGL::SyncFragmentColorClampState() {
  989. auto& gpu = system.GPU().Maxwell3D();
  990. auto& flags = gpu.dirty.flags;
  991. if (!flags[Dirty::FragmentClampColor]) {
  992. return;
  993. }
  994. flags[Dirty::FragmentClampColor] = false;
  995. glClampColor(GL_CLAMP_FRAGMENT_COLOR, gpu.regs.frag_color_clamp ? GL_TRUE : GL_FALSE);
  996. }
  997. void RasterizerOpenGL::SyncBlendState() {
  998. auto& gpu = system.GPU().Maxwell3D();
  999. auto& flags = gpu.dirty.flags;
  1000. const auto& regs = gpu.regs;
  1001. if (flags[Dirty::BlendColor]) {
  1002. flags[Dirty::BlendColor] = false;
  1003. glBlendColor(regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  1004. regs.blend_color.a);
  1005. }
  1006. // TODO(Rodrigo): Revisit blending, there are several registers we are not reading
  1007. if (!flags[Dirty::BlendStates]) {
  1008. return;
  1009. }
  1010. flags[Dirty::BlendStates] = false;
  1011. if (!regs.independent_blend_enable) {
  1012. if (!regs.blend.enable[0]) {
  1013. glDisable(GL_BLEND);
  1014. return;
  1015. }
  1016. glEnable(GL_BLEND);
  1017. glBlendFuncSeparate(MaxwellToGL::BlendFunc(regs.blend.factor_source_rgb),
  1018. MaxwellToGL::BlendFunc(regs.blend.factor_dest_rgb),
  1019. MaxwellToGL::BlendFunc(regs.blend.factor_source_a),
  1020. MaxwellToGL::BlendFunc(regs.blend.factor_dest_a));
  1021. glBlendEquationSeparate(MaxwellToGL::BlendEquation(regs.blend.equation_rgb),
  1022. MaxwellToGL::BlendEquation(regs.blend.equation_a));
  1023. return;
  1024. }
  1025. const bool force = flags[Dirty::BlendIndependentEnabled];
  1026. flags[Dirty::BlendIndependentEnabled] = false;
  1027. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  1028. if (!force && !flags[Dirty::BlendState0 + i]) {
  1029. continue;
  1030. }
  1031. flags[Dirty::BlendState0 + i] = false;
  1032. if (!regs.blend.enable[i]) {
  1033. glDisablei(GL_BLEND, static_cast<GLuint>(i));
  1034. continue;
  1035. }
  1036. glEnablei(GL_BLEND, static_cast<GLuint>(i));
  1037. const auto& src = regs.independent_blend[i];
  1038. glBlendFuncSeparatei(static_cast<GLuint>(i), MaxwellToGL::BlendFunc(src.factor_source_rgb),
  1039. MaxwellToGL::BlendFunc(src.factor_dest_rgb),
  1040. MaxwellToGL::BlendFunc(src.factor_source_a),
  1041. MaxwellToGL::BlendFunc(src.factor_dest_a));
  1042. glBlendEquationSeparatei(static_cast<GLuint>(i),
  1043. MaxwellToGL::BlendEquation(src.equation_rgb),
  1044. MaxwellToGL::BlendEquation(src.equation_a));
  1045. }
  1046. }
  1047. void RasterizerOpenGL::SyncLogicOpState() {
  1048. auto& gpu = system.GPU().Maxwell3D();
  1049. auto& flags = gpu.dirty.flags;
  1050. if (!flags[Dirty::LogicOp]) {
  1051. return;
  1052. }
  1053. flags[Dirty::LogicOp] = false;
  1054. const auto& regs = gpu.regs;
  1055. if (regs.logic_op.enable) {
  1056. glEnable(GL_COLOR_LOGIC_OP);
  1057. glLogicOp(MaxwellToGL::LogicOp(regs.logic_op.operation));
  1058. } else {
  1059. glDisable(GL_COLOR_LOGIC_OP);
  1060. }
  1061. }
  1062. void RasterizerOpenGL::SyncScissorTest() {
  1063. auto& gpu = system.GPU().Maxwell3D();
  1064. auto& flags = gpu.dirty.flags;
  1065. if (!flags[Dirty::Scissors]) {
  1066. return;
  1067. }
  1068. flags[Dirty::Scissors] = false;
  1069. const auto& regs = gpu.regs;
  1070. for (std::size_t index = 0; index < Maxwell::NumViewports; ++index) {
  1071. if (!flags[Dirty::Scissor0 + index]) {
  1072. continue;
  1073. }
  1074. flags[Dirty::Scissor0 + index] = false;
  1075. const auto& src = regs.scissor_test[index];
  1076. if (src.enable) {
  1077. glEnablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  1078. glScissorIndexed(static_cast<GLuint>(index), src.min_x, src.min_y,
  1079. src.max_x - src.min_x, src.max_y - src.min_y);
  1080. } else {
  1081. glDisablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  1082. }
  1083. }
  1084. }
  1085. void RasterizerOpenGL::SyncPointState() {
  1086. auto& gpu = system.GPU().Maxwell3D();
  1087. auto& flags = gpu.dirty.flags;
  1088. if (!flags[Dirty::PointSize]) {
  1089. return;
  1090. }
  1091. flags[Dirty::PointSize] = false;
  1092. oglEnable(GL_POINT_SPRITE, gpu.regs.point_sprite_enable);
  1093. if (gpu.regs.vp_point_size.enable) {
  1094. // By definition of GL_POINT_SIZE, it only matters if GL_PROGRAM_POINT_SIZE is disabled.
  1095. glEnable(GL_PROGRAM_POINT_SIZE);
  1096. return;
  1097. }
  1098. // Limit the point size to 1 since nouveau sometimes sets a point size of 0 (and that's invalid
  1099. // in OpenGL).
  1100. glPointSize(std::max(1.0f, gpu.regs.point_size));
  1101. glDisable(GL_PROGRAM_POINT_SIZE);
  1102. }
  1103. void RasterizerOpenGL::SyncPolygonOffset() {
  1104. auto& gpu = system.GPU().Maxwell3D();
  1105. auto& flags = gpu.dirty.flags;
  1106. if (!flags[Dirty::PolygonOffset]) {
  1107. return;
  1108. }
  1109. flags[Dirty::PolygonOffset] = false;
  1110. const auto& regs = gpu.regs;
  1111. oglEnable(GL_POLYGON_OFFSET_FILL, regs.polygon_offset_fill_enable);
  1112. oglEnable(GL_POLYGON_OFFSET_LINE, regs.polygon_offset_line_enable);
  1113. oglEnable(GL_POLYGON_OFFSET_POINT, regs.polygon_offset_point_enable);
  1114. if (regs.polygon_offset_fill_enable || regs.polygon_offset_line_enable ||
  1115. regs.polygon_offset_point_enable) {
  1116. // Hardware divides polygon offset units by two
  1117. glPolygonOffsetClamp(regs.polygon_offset_factor, regs.polygon_offset_units / 2.0f,
  1118. regs.polygon_offset_clamp);
  1119. }
  1120. }
  1121. void RasterizerOpenGL::SyncAlphaTest() {
  1122. auto& gpu = system.GPU().Maxwell3D();
  1123. auto& flags = gpu.dirty.flags;
  1124. if (!flags[Dirty::AlphaTest]) {
  1125. return;
  1126. }
  1127. flags[Dirty::AlphaTest] = false;
  1128. const auto& regs = gpu.regs;
  1129. if (regs.alpha_test_enabled && regs.rt_control.count > 1) {
  1130. LOG_WARNING(Render_OpenGL, "Alpha testing with more than one render target is not tested");
  1131. }
  1132. if (regs.alpha_test_enabled) {
  1133. glEnable(GL_ALPHA_TEST);
  1134. glAlphaFunc(MaxwellToGL::ComparisonOp(regs.alpha_test_func), regs.alpha_test_ref);
  1135. } else {
  1136. glDisable(GL_ALPHA_TEST);
  1137. }
  1138. }
  1139. void RasterizerOpenGL::SyncFramebufferSRGB() {
  1140. auto& gpu = system.GPU().Maxwell3D();
  1141. auto& flags = gpu.dirty.flags;
  1142. if (!flags[Dirty::FramebufferSRGB]) {
  1143. return;
  1144. }
  1145. flags[Dirty::FramebufferSRGB] = false;
  1146. oglEnable(GL_FRAMEBUFFER_SRGB, gpu.regs.framebuffer_srgb);
  1147. }
  1148. void RasterizerOpenGL::BeginTransformFeedback(GLenum primitive_mode) {
  1149. const auto& regs = system.GPU().Maxwell3D().regs;
  1150. if (regs.tfb_enabled == 0) {
  1151. return;
  1152. }
  1153. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationControl) ||
  1154. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationEval) ||
  1155. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::Geometry));
  1156. for (std::size_t index = 0; index < Maxwell::NumTransformFeedbackBuffers; ++index) {
  1157. const auto& binding = regs.tfb_bindings[index];
  1158. if (!binding.buffer_enable) {
  1159. if (enabled_transform_feedback_buffers[index]) {
  1160. glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, static_cast<GLuint>(index), 0, 0,
  1161. 0);
  1162. }
  1163. enabled_transform_feedback_buffers[index] = false;
  1164. continue;
  1165. }
  1166. enabled_transform_feedback_buffers[index] = true;
  1167. auto& tfb_buffer = transform_feedback_buffers[index];
  1168. tfb_buffer.Create();
  1169. const GLuint handle = tfb_buffer.handle;
  1170. const std::size_t size = binding.buffer_size;
  1171. glNamedBufferData(handle, static_cast<GLsizeiptr>(size), nullptr, GL_STREAM_COPY);
  1172. glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, static_cast<GLuint>(index), handle, 0,
  1173. static_cast<GLsizeiptr>(size));
  1174. }
  1175. glBeginTransformFeedback(GL_POINTS);
  1176. }
  1177. void RasterizerOpenGL::EndTransformFeedback() {
  1178. const auto& regs = system.GPU().Maxwell3D().regs;
  1179. if (regs.tfb_enabled == 0) {
  1180. return;
  1181. }
  1182. glEndTransformFeedback();
  1183. for (std::size_t index = 0; index < Maxwell::NumTransformFeedbackBuffers; ++index) {
  1184. const auto& binding = regs.tfb_bindings[index];
  1185. if (!binding.buffer_enable) {
  1186. continue;
  1187. }
  1188. UNIMPLEMENTED_IF(binding.buffer_offset != 0);
  1189. const GLuint handle = transform_feedback_buffers[index].handle;
  1190. const GPUVAddr gpu_addr = binding.Address();
  1191. const std::size_t size = binding.buffer_size;
  1192. const auto [dest_buffer, offset] = buffer_cache.UploadMemory(gpu_addr, size, 4, true);
  1193. glCopyNamedBufferSubData(handle, *dest_buffer, 0, offset, static_cast<GLsizeiptr>(size));
  1194. }
  1195. }
  1196. } // namespace OpenGL