gl_rasterizer.cpp 51 KB

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