gl_rasterizer.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  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/gl_shader_gen.h"
  31. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  32. #include "video_core/renderer_opengl/renderer_opengl.h"
  33. namespace OpenGL {
  34. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  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. template <typename Engine, typename Entry>
  51. Tegra::Texture::FullTextureInfo GetTextureInfo(const Engine& engine, const Entry& entry,
  52. Tegra::Engines::ShaderType shader_type,
  53. 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 GLShader::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. void oglEnablei(GLenum cap, bool state, GLuint index) {
  84. (state ? glEnablei : glDisablei)(cap, index);
  85. }
  86. } // Anonymous namespace
  87. RasterizerOpenGL::RasterizerOpenGL(Core::System& system, Core::Frontend::EmuWindow& emu_window,
  88. ScreenInfo& info)
  89. : RasterizerAccelerated{system.Memory()}, texture_cache{system, *this, device},
  90. shader_cache{*this, system, emu_window, device}, query_cache{system, *this}, system{system},
  91. screen_info{info}, buffer_cache{*this, system, device, STREAM_BUFFER_SIZE} {
  92. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  93. state.draw.shader_program = 0;
  94. state.Apply();
  95. LOG_DEBUG(Render_OpenGL, "Sync fixed function OpenGL state here");
  96. CheckExtensions();
  97. }
  98. RasterizerOpenGL::~RasterizerOpenGL() {}
  99. void RasterizerOpenGL::CheckExtensions() {
  100. if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
  101. LOG_WARNING(
  102. Render_OpenGL,
  103. "Anisotropic filter is not supported! This can cause graphical issues in some games.");
  104. }
  105. }
  106. GLuint RasterizerOpenGL::SetupVertexFormat() {
  107. auto& gpu = system.GPU().Maxwell3D();
  108. const auto& regs = gpu.regs;
  109. MICROPROFILE_SCOPE(OpenGL_VAO);
  110. auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
  111. auto& vao_entry = iter->second;
  112. if (is_cache_miss) {
  113. vao_entry.Create();
  114. const GLuint vao = vao_entry.handle;
  115. // Eventhough we are using DSA to create this vertex array, there is a bug on Intel's blob
  116. // that fails to properly create the vertex array if it's not bound even after creating it
  117. // with glCreateVertexArrays
  118. state.draw.vertex_array = vao;
  119. state.ApplyVertexArrayState();
  120. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  121. // Enables the first 16 vertex attributes always, as we don't know which ones are actually
  122. // used until shader time. Note, Tegra technically supports 32, but we're capping this to 16
  123. // for now to avoid OpenGL errors.
  124. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  125. // assume every shader uses them all.
  126. for (u32 index = 0; index < 16; ++index) {
  127. const auto& attrib = regs.vertex_attrib_format[index];
  128. // Ignore invalid attributes.
  129. if (!attrib.IsValid())
  130. continue;
  131. const auto& buffer = regs.vertex_array[attrib.buffer];
  132. LOG_TRACE(Render_OpenGL,
  133. "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  134. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  135. attrib.offset.Value(), attrib.IsNormalized());
  136. ASSERT(buffer.IsEnabled());
  137. glEnableVertexArrayAttrib(vao, index);
  138. if (attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::SignedInt ||
  139. attrib.type ==
  140. Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::UnsignedInt) {
  141. glVertexArrayAttribIFormat(vao, index, attrib.ComponentCount(),
  142. MaxwellToGL::VertexType(attrib), attrib.offset);
  143. } else {
  144. glVertexArrayAttribFormat(
  145. vao, index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  146. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  147. }
  148. glVertexArrayAttribBinding(vao, index, attrib.buffer);
  149. }
  150. }
  151. state.draw.vertex_array = vao_entry.handle;
  152. return vao_entry.handle;
  153. }
  154. void RasterizerOpenGL::SetupVertexBuffer(GLuint vao) {
  155. auto& gpu = system.GPU().Maxwell3D();
  156. const auto& regs = gpu.regs;
  157. MICROPROFILE_SCOPE(OpenGL_VB);
  158. // Upload all guest vertex arrays sequentially to our buffer
  159. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  160. const auto& vertex_array = regs.vertex_array[index];
  161. if (!vertex_array.IsEnabled())
  162. continue;
  163. const GPUVAddr start = vertex_array.StartAddress();
  164. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  165. ASSERT(end > start);
  166. const u64 size = end - start + 1;
  167. const auto [vertex_buffer, vertex_buffer_offset] = buffer_cache.UploadMemory(start, size);
  168. // Bind the vertex array to the buffer at the current offset.
  169. vertex_array_pushbuffer.SetVertexBuffer(index, vertex_buffer, vertex_buffer_offset,
  170. vertex_array.stride);
  171. if (regs.instanced_arrays.IsInstancingEnabled(index) && vertex_array.divisor != 0) {
  172. // Enable vertex buffer instancing with the specified divisor.
  173. glVertexArrayBindingDivisor(vao, index, vertex_array.divisor);
  174. } else {
  175. // Disable the vertex buffer instancing.
  176. glVertexArrayBindingDivisor(vao, index, 0);
  177. }
  178. }
  179. }
  180. void RasterizerOpenGL::SetupVertexInstances(GLuint vao) {
  181. auto& gpu = system.GPU().Maxwell3D();
  182. const auto& regs = gpu.regs;
  183. // Upload all guest vertex arrays sequentially to our buffer
  184. for (u32 index = 0; index < 16; ++index) {
  185. if (regs.instanced_arrays.IsInstancingEnabled(index) &&
  186. regs.vertex_array[index].divisor != 0) {
  187. // Enable vertex buffer instancing with the specified divisor.
  188. glVertexArrayBindingDivisor(vao, index, regs.vertex_array[index].divisor);
  189. } else {
  190. // Disable the vertex buffer instancing.
  191. glVertexArrayBindingDivisor(vao, index, 0);
  192. }
  193. }
  194. }
  195. GLintptr RasterizerOpenGL::SetupIndexBuffer() {
  196. MICROPROFILE_SCOPE(OpenGL_Index);
  197. const auto& regs = system.GPU().Maxwell3D().regs;
  198. const std::size_t size = CalculateIndexBufferSize();
  199. const auto [buffer, offset] = buffer_cache.UploadMemory(regs.index_array.IndexStart(), size);
  200. vertex_array_pushbuffer.SetIndexBuffer(buffer);
  201. return offset;
  202. }
  203. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  204. MICROPROFILE_SCOPE(OpenGL_Shader);
  205. auto& gpu = system.GPU().Maxwell3D();
  206. std::array<bool, Maxwell::NumClipDistances> clip_distances{};
  207. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  208. const auto& shader_config = gpu.regs.shader_config[index];
  209. const auto program{static_cast<Maxwell::ShaderProgram>(index)};
  210. // Skip stages that are not enabled
  211. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  212. switch (program) {
  213. case Maxwell::ShaderProgram::Geometry:
  214. shader_program_manager->UseTrivialGeometryShader();
  215. break;
  216. case Maxwell::ShaderProgram::Fragment:
  217. shader_program_manager->UseTrivialFragmentShader();
  218. break;
  219. default:
  220. break;
  221. }
  222. continue;
  223. }
  224. // Currently this stages are not supported in the OpenGL backend.
  225. // Todo(Blinkhawk): Port tesselation shaders from Vulkan to OpenGL
  226. if (program == Maxwell::ShaderProgram::TesselationControl) {
  227. continue;
  228. } else if (program == Maxwell::ShaderProgram::TesselationEval) {
  229. continue;
  230. }
  231. Shader shader{shader_cache.GetStageProgram(program)};
  232. // Stage indices are 0 - 5
  233. const std::size_t stage = index == 0 ? 0 : index - 1;
  234. SetupDrawConstBuffers(stage, shader);
  235. SetupDrawGlobalMemory(stage, shader);
  236. SetupDrawTextures(stage, shader);
  237. SetupDrawImages(stage, shader);
  238. const ProgramVariant variant(primitive_mode);
  239. const auto program_handle = shader->GetHandle(variant);
  240. switch (program) {
  241. case Maxwell::ShaderProgram::VertexA:
  242. case Maxwell::ShaderProgram::VertexB:
  243. shader_program_manager->UseProgrammableVertexShader(program_handle);
  244. break;
  245. case Maxwell::ShaderProgram::Geometry:
  246. shader_program_manager->UseProgrammableGeometryShader(program_handle);
  247. break;
  248. case Maxwell::ShaderProgram::Fragment:
  249. shader_program_manager->UseProgrammableFragmentShader(program_handle);
  250. break;
  251. default:
  252. UNIMPLEMENTED_MSG("Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  253. shader_config.enable.Value(), shader_config.offset);
  254. }
  255. // Workaround for Intel drivers.
  256. // When a clip distance is enabled but not set in the shader it crops parts of the screen
  257. // (sometimes it's half the screen, sometimes three quarters). To avoid this, enable the
  258. // clip distances only when it's written by a shader stage.
  259. for (std::size_t i = 0; i < Maxwell::NumClipDistances; ++i) {
  260. clip_distances[i] = clip_distances[i] || shader->GetShaderEntries().clip_distances[i];
  261. }
  262. // When VertexA is enabled, we have dual vertex shaders
  263. if (program == Maxwell::ShaderProgram::VertexA) {
  264. // VertexB was combined with VertexA, so we skip the VertexB iteration
  265. ++index;
  266. }
  267. }
  268. SyncClipEnabled(clip_distances);
  269. }
  270. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  271. const auto& regs = system.GPU().Maxwell3D().regs;
  272. std::size_t size = 0;
  273. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  274. if (!regs.vertex_array[index].IsEnabled())
  275. continue;
  276. const GPUVAddr start = regs.vertex_array[index].StartAddress();
  277. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  278. ASSERT(end > start);
  279. size += end - start + 1;
  280. }
  281. return size;
  282. }
  283. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  284. const auto& regs = system.GPU().Maxwell3D().regs;
  285. return static_cast<std::size_t>(regs.index_array.count) *
  286. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  287. }
  288. void RasterizerOpenGL::LoadDiskResources(const std::atomic_bool& stop_loading,
  289. const VideoCore::DiskResourceLoadCallback& callback) {
  290. shader_cache.LoadDiskCache(stop_loading, callback);
  291. }
  292. void RasterizerOpenGL::ConfigureFramebuffers() {
  293. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  294. auto& gpu = system.GPU().Maxwell3D();
  295. texture_cache.GuardRenderTargets(true);
  296. View depth_surface = texture_cache.GetDepthBufferSurface(true);
  297. const auto& regs = gpu.regs;
  298. state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0;
  299. UNIMPLEMENTED_IF(regs.rt_separate_frag_data == 0);
  300. // Bind the framebuffer surfaces
  301. FramebufferCacheKey key;
  302. const auto colors_count = static_cast<std::size_t>(regs.rt_control.count);
  303. for (std::size_t index = 0; index < colors_count; ++index) {
  304. View color_surface{texture_cache.GetColorBufferSurface(index, true)};
  305. if (!color_surface) {
  306. continue;
  307. }
  308. // Assume that a surface will be written to if it is used as a framebuffer, even
  309. // if the shader doesn't actually write to it.
  310. texture_cache.MarkColorBufferInUse(index);
  311. key.SetAttachment(index, regs.rt_control.GetMap(index));
  312. key.colors[index] = std::move(color_surface);
  313. }
  314. if (depth_surface) {
  315. // Assume that a surface will be written to if it is used as a framebuffer, even if
  316. // the shader doesn't actually write to it.
  317. texture_cache.MarkDepthBufferInUse();
  318. key.zeta = std::move(depth_surface);
  319. }
  320. texture_cache.GuardRenderTargets(false);
  321. state.draw.draw_framebuffer = framebuffer_cache.GetFramebuffer(key);
  322. SyncViewport(state);
  323. }
  324. void RasterizerOpenGL::ConfigureClearFramebuffer(OpenGLState& current_state, bool using_color_fb,
  325. bool using_depth_fb, bool using_stencil_fb) {
  326. using VideoCore::Surface::SurfaceType;
  327. auto& gpu = system.GPU().Maxwell3D();
  328. const auto& regs = gpu.regs;
  329. texture_cache.GuardRenderTargets(true);
  330. View color_surface;
  331. if (using_color_fb) {
  332. color_surface = texture_cache.GetColorBufferSurface(regs.clear_buffers.RT, false);
  333. }
  334. View depth_surface;
  335. if (using_depth_fb || using_stencil_fb) {
  336. depth_surface = texture_cache.GetDepthBufferSurface(false);
  337. }
  338. texture_cache.GuardRenderTargets(false);
  339. FramebufferCacheKey key;
  340. key.colors[0] = color_surface;
  341. key.zeta = depth_surface;
  342. current_state.draw.draw_framebuffer = framebuffer_cache.GetFramebuffer(key);
  343. current_state.ApplyFramebufferState();
  344. }
  345. void RasterizerOpenGL::Clear() {
  346. const auto& maxwell3d = system.GPU().Maxwell3D();
  347. if (!maxwell3d.ShouldExecute()) {
  348. return;
  349. }
  350. const auto& regs = maxwell3d.regs;
  351. bool use_color{};
  352. bool use_depth{};
  353. bool use_stencil{};
  354. OpenGLState prev_state{OpenGLState::GetCurState()};
  355. SCOPE_EXIT({ prev_state.Apply(); });
  356. OpenGLState clear_state{OpenGLState::GetCurState()};
  357. clear_state.SetDefaultViewports();
  358. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  359. regs.clear_buffers.A) {
  360. use_color = true;
  361. }
  362. if (use_color) {
  363. clear_state.color_mask[0].red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
  364. clear_state.color_mask[0].green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
  365. clear_state.color_mask[0].blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
  366. clear_state.color_mask[0].alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
  367. }
  368. if (regs.clear_buffers.Z) {
  369. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  370. use_depth = true;
  371. // Always enable the depth write when clearing the depth buffer. The depth write mask is
  372. // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to
  373. // true.
  374. clear_state.depth.test_enabled = true;
  375. clear_state.depth.test_func = GL_ALWAYS;
  376. clear_state.depth.write_mask = GL_TRUE;
  377. }
  378. if (regs.clear_buffers.S) {
  379. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear stencil but buffer is not enabled!");
  380. use_stencil = true;
  381. clear_state.stencil.test_enabled = true;
  382. if (regs.clear_flags.stencil) {
  383. // Stencil affects the clear so fill it with the used masks
  384. clear_state.stencil.front.test_func = GL_ALWAYS;
  385. clear_state.stencil.front.test_mask = regs.stencil_front_func_mask;
  386. clear_state.stencil.front.action_stencil_fail = GL_KEEP;
  387. clear_state.stencil.front.action_depth_fail = GL_KEEP;
  388. clear_state.stencil.front.action_depth_pass = GL_KEEP;
  389. clear_state.stencil.front.write_mask = regs.stencil_front_mask;
  390. if (regs.stencil_two_side_enable) {
  391. clear_state.stencil.back.test_func = GL_ALWAYS;
  392. clear_state.stencil.back.test_mask = regs.stencil_back_func_mask;
  393. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  394. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  395. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  396. clear_state.stencil.back.write_mask = regs.stencil_back_mask;
  397. } else {
  398. clear_state.stencil.back.test_func = GL_ALWAYS;
  399. clear_state.stencil.back.test_mask = 0xFFFFFFFF;
  400. clear_state.stencil.back.write_mask = 0xFFFFFFFF;
  401. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  402. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  403. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  404. }
  405. }
  406. }
  407. if (!use_color && !use_depth && !use_stencil) {
  408. // No color surface nor depth/stencil surface are enabled
  409. return;
  410. }
  411. ConfigureClearFramebuffer(clear_state, use_color, use_depth, use_stencil);
  412. SyncViewport(clear_state);
  413. SyncRasterizeEnable(clear_state);
  414. if (regs.clear_flags.scissor) {
  415. SyncScissorTest(clear_state);
  416. }
  417. if (regs.clear_flags.viewport) {
  418. clear_state.EmulateViewportWithScissor();
  419. }
  420. clear_state.Apply();
  421. if (use_color) {
  422. glClearBufferfv(GL_COLOR, 0, regs.clear_color);
  423. }
  424. if (use_depth && use_stencil) {
  425. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  426. } else if (use_depth) {
  427. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  428. } else if (use_stencil) {
  429. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  430. }
  431. ++num_queued_commands;
  432. }
  433. void RasterizerOpenGL::Draw(bool is_indexed, bool is_instanced) {
  434. MICROPROFILE_SCOPE(OpenGL_Drawing);
  435. auto& gpu = system.GPU().Maxwell3D();
  436. const auto& regs = gpu.regs;
  437. query_cache.UpdateCounters();
  438. SyncRasterizeEnable(state);
  439. SyncColorMask();
  440. SyncFragmentColorClampState();
  441. SyncMultiSampleState();
  442. SyncDepthTestState();
  443. SyncStencilTestState();
  444. SyncBlendState();
  445. SyncLogicOpState();
  446. SyncCullMode();
  447. SyncPrimitiveRestart();
  448. SyncScissorTest(state);
  449. SyncTransformFeedback();
  450. SyncPointState();
  451. SyncPolygonOffset();
  452. SyncAlphaTest();
  453. buffer_cache.Acquire();
  454. std::size_t buffer_size = CalculateVertexArraysSize();
  455. // Add space for index buffer
  456. if (is_indexed) {
  457. buffer_size = Common::AlignUp(buffer_size, 4) + CalculateIndexBufferSize();
  458. }
  459. // Uniform space for the 5 shader stages
  460. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) +
  461. (sizeof(GLShader::MaxwellUniformData) + device.GetUniformBufferAlignment()) *
  462. Maxwell::MaxShaderStage;
  463. // Add space for at least 18 constant buffers
  464. buffer_size += Maxwell::MaxConstBuffers *
  465. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  466. // Prepare the vertex array.
  467. buffer_cache.Map(buffer_size);
  468. // Prepare vertex array format.
  469. const GLuint vao = SetupVertexFormat();
  470. vertex_array_pushbuffer.Setup(vao);
  471. // Upload vertex and index data.
  472. SetupVertexBuffer(vao);
  473. SetupVertexInstances(vao);
  474. GLintptr index_buffer_offset;
  475. if (is_indexed) {
  476. index_buffer_offset = SetupIndexBuffer();
  477. }
  478. // Prepare packed bindings.
  479. bind_ubo_pushbuffer.Setup();
  480. bind_ssbo_pushbuffer.Setup();
  481. // Setup emulation uniform buffer.
  482. GLShader::MaxwellUniformData ubo;
  483. ubo.SetFromRegs(gpu);
  484. const auto [buffer, offset] =
  485. buffer_cache.UploadHostMemory(&ubo, sizeof(ubo), device.GetUniformBufferAlignment());
  486. bind_ubo_pushbuffer.Push(EmulationUniformBlockBinding, buffer, offset,
  487. static_cast<GLsizeiptr>(sizeof(ubo)));
  488. // Setup shaders and their used resources.
  489. texture_cache.GuardSamplers(true);
  490. const GLenum primitive_mode = MaxwellToGL::PrimitiveTopology(gpu.regs.draw.topology);
  491. SetupShaders(primitive_mode);
  492. texture_cache.GuardSamplers(false);
  493. ConfigureFramebuffers();
  494. // Signal the buffer cache that we are not going to upload more things.
  495. const bool invalidate = buffer_cache.Unmap();
  496. // Now that we are no longer uploading data, we can safely bind the buffers to OpenGL.
  497. vertex_array_pushbuffer.Bind();
  498. bind_ubo_pushbuffer.Bind();
  499. bind_ssbo_pushbuffer.Bind();
  500. shader_program_manager->ApplyTo(state);
  501. state.Apply();
  502. if (texture_cache.TextureBarrier()) {
  503. glTextureBarrier();
  504. }
  505. ++num_queued_commands;
  506. const GLuint base_instance = static_cast<GLuint>(gpu.regs.vb_base_instance);
  507. const GLsizei num_instances =
  508. static_cast<GLsizei>(is_instanced ? gpu.mme_draw.instance_count : 1);
  509. if (is_indexed) {
  510. const GLint base_vertex = static_cast<GLint>(gpu.regs.vb_element_base);
  511. const GLsizei num_vertices = static_cast<GLsizei>(gpu.regs.index_array.count);
  512. const GLvoid* offset = reinterpret_cast<const GLvoid*>(index_buffer_offset);
  513. const GLenum format = MaxwellToGL::IndexFormat(gpu.regs.index_array.format);
  514. if (num_instances == 1 && base_instance == 0 && base_vertex == 0) {
  515. glDrawElements(primitive_mode, num_vertices, format, offset);
  516. } else if (num_instances == 1 && base_instance == 0) {
  517. glDrawElementsBaseVertex(primitive_mode, num_vertices, format, offset, base_vertex);
  518. } else if (base_vertex == 0 && base_instance == 0) {
  519. glDrawElementsInstanced(primitive_mode, num_vertices, format, offset, num_instances);
  520. } else if (base_vertex == 0) {
  521. glDrawElementsInstancedBaseInstance(primitive_mode, num_vertices, format, offset,
  522. num_instances, base_instance);
  523. } else if (base_instance == 0) {
  524. glDrawElementsInstancedBaseVertex(primitive_mode, num_vertices, format, offset,
  525. num_instances, base_vertex);
  526. } else {
  527. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, num_vertices, format,
  528. offset, num_instances, base_vertex,
  529. base_instance);
  530. }
  531. } else {
  532. const GLint base_vertex = static_cast<GLint>(gpu.regs.vertex_buffer.first);
  533. const GLsizei num_vertices = static_cast<GLsizei>(gpu.regs.vertex_buffer.count);
  534. if (num_instances == 1 && base_instance == 0) {
  535. glDrawArrays(primitive_mode, base_vertex, num_vertices);
  536. } else if (base_instance == 0) {
  537. glDrawArraysInstanced(primitive_mode, base_vertex, num_vertices, num_instances);
  538. } else {
  539. glDrawArraysInstancedBaseInstance(primitive_mode, base_vertex, num_vertices,
  540. num_instances, base_instance);
  541. }
  542. }
  543. }
  544. void RasterizerOpenGL::DispatchCompute(GPUVAddr code_addr) {
  545. if (device.HasBrokenCompute()) {
  546. return;
  547. }
  548. buffer_cache.Acquire();
  549. auto kernel = shader_cache.GetComputeKernel(code_addr);
  550. SetupComputeTextures(kernel);
  551. SetupComputeImages(kernel);
  552. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  553. const ProgramVariant variant(launch_desc.block_dim_x, launch_desc.block_dim_y,
  554. launch_desc.block_dim_z, launch_desc.shared_alloc,
  555. launch_desc.local_pos_alloc);
  556. state.draw.shader_program = kernel->GetHandle(variant);
  557. state.draw.program_pipeline = 0;
  558. const std::size_t buffer_size =
  559. Tegra::Engines::KeplerCompute::NumConstBuffers *
  560. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  561. buffer_cache.Map(buffer_size);
  562. bind_ubo_pushbuffer.Setup();
  563. bind_ssbo_pushbuffer.Setup();
  564. SetupComputeConstBuffers(kernel);
  565. SetupComputeGlobalMemory(kernel);
  566. buffer_cache.Unmap();
  567. bind_ubo_pushbuffer.Bind();
  568. bind_ssbo_pushbuffer.Bind();
  569. state.ApplyTextures();
  570. state.ApplyImages();
  571. state.ApplyShaderProgram();
  572. state.ApplyProgramPipeline();
  573. glDispatchCompute(launch_desc.grid_dim_x, launch_desc.grid_dim_y, launch_desc.grid_dim_z);
  574. ++num_queued_commands;
  575. }
  576. void RasterizerOpenGL::ResetCounter(VideoCore::QueryType type) {
  577. query_cache.ResetCounter(type);
  578. }
  579. void RasterizerOpenGL::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  580. std::optional<u64> timestamp) {
  581. query_cache.Query(gpu_addr, type, timestamp);
  582. }
  583. void RasterizerOpenGL::FlushAll() {}
  584. void RasterizerOpenGL::FlushRegion(CacheAddr addr, u64 size) {
  585. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  586. if (!addr || !size) {
  587. return;
  588. }
  589. texture_cache.FlushRegion(addr, size);
  590. buffer_cache.FlushRegion(addr, size);
  591. query_cache.FlushRegion(addr, size);
  592. }
  593. void RasterizerOpenGL::InvalidateRegion(CacheAddr addr, u64 size) {
  594. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  595. if (!addr || !size) {
  596. return;
  597. }
  598. texture_cache.InvalidateRegion(addr, size);
  599. shader_cache.InvalidateRegion(addr, size);
  600. buffer_cache.InvalidateRegion(addr, size);
  601. query_cache.InvalidateRegion(addr, size);
  602. }
  603. void RasterizerOpenGL::FlushAndInvalidateRegion(CacheAddr addr, u64 size) {
  604. if (Settings::values.use_accurate_gpu_emulation) {
  605. FlushRegion(addr, size);
  606. }
  607. InvalidateRegion(addr, size);
  608. }
  609. void RasterizerOpenGL::FlushCommands() {
  610. // Only flush when we have commands queued to OpenGL.
  611. if (num_queued_commands == 0) {
  612. return;
  613. }
  614. num_queued_commands = 0;
  615. glFlush();
  616. }
  617. void RasterizerOpenGL::TickFrame() {
  618. // Ticking a frame means that buffers will be swapped, calling glFlush implicitly.
  619. num_queued_commands = 0;
  620. buffer_cache.TickFrame();
  621. }
  622. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  623. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  624. const Tegra::Engines::Fermi2D::Config& copy_config) {
  625. MICROPROFILE_SCOPE(OpenGL_Blits);
  626. texture_cache.DoFermiCopy(src, dst, copy_config);
  627. return true;
  628. }
  629. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  630. VAddr framebuffer_addr, u32 pixel_stride) {
  631. if (!framebuffer_addr) {
  632. return {};
  633. }
  634. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  635. const auto surface{
  636. texture_cache.TryFindFramebufferSurface(system.Memory().GetPointer(framebuffer_addr))};
  637. if (!surface) {
  638. return {};
  639. }
  640. // Verify that the cached surface is the same size and format as the requested framebuffer
  641. const auto& params{surface->GetSurfaceParams()};
  642. const auto& pixel_format{
  643. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  644. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  645. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  646. if (params.pixel_format != pixel_format) {
  647. LOG_DEBUG(Render_OpenGL, "Framebuffer pixel_format is different");
  648. }
  649. screen_info.display_texture = surface->GetTexture();
  650. screen_info.display_srgb = surface->GetSurfaceParams().srgb_conversion;
  651. return true;
  652. }
  653. void RasterizerOpenGL::SetupDrawConstBuffers(std::size_t stage_index, const Shader& shader) {
  654. MICROPROFILE_SCOPE(OpenGL_UBO);
  655. const auto& stages = system.GPU().Maxwell3D().state.shader_stages;
  656. const auto& shader_stage = stages[stage_index];
  657. u32 binding = device.GetBaseBindings(stage_index).uniform_buffer;
  658. for (const auto& entry : shader->GetShaderEntries().const_buffers) {
  659. const auto& buffer = shader_stage.const_buffers[entry.GetIndex()];
  660. SetupConstBuffer(binding++, buffer, entry);
  661. }
  662. }
  663. void RasterizerOpenGL::SetupComputeConstBuffers(const Shader& kernel) {
  664. MICROPROFILE_SCOPE(OpenGL_UBO);
  665. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  666. u32 binding = 0;
  667. for (const auto& entry : kernel->GetShaderEntries().const_buffers) {
  668. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  669. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  670. Tegra::Engines::ConstBufferInfo buffer;
  671. buffer.address = config.Address();
  672. buffer.size = config.size;
  673. buffer.enabled = mask[entry.GetIndex()];
  674. SetupConstBuffer(binding++, buffer, entry);
  675. }
  676. }
  677. void RasterizerOpenGL::SetupConstBuffer(u32 binding, const Tegra::Engines::ConstBufferInfo& buffer,
  678. const GLShader::ConstBufferEntry& entry) {
  679. if (!buffer.enabled) {
  680. // Set values to zero to unbind buffers
  681. bind_ubo_pushbuffer.Push(binding, buffer_cache.GetEmptyBuffer(sizeof(float)), 0,
  682. sizeof(float));
  683. return;
  684. }
  685. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  686. // UBO alignment requirements.
  687. const std::size_t size = Common::AlignUp(GetConstBufferSize(buffer, entry), sizeof(GLvec4));
  688. const auto alignment = device.GetUniformBufferAlignment();
  689. const auto [cbuf, offset] = buffer_cache.UploadMemory(buffer.address, size, alignment, false,
  690. device.HasFastBufferSubData());
  691. bind_ubo_pushbuffer.Push(binding, cbuf, offset, size);
  692. }
  693. void RasterizerOpenGL::SetupDrawGlobalMemory(std::size_t stage_index, const Shader& shader) {
  694. auto& gpu{system.GPU()};
  695. auto& memory_manager{gpu.MemoryManager()};
  696. const auto cbufs{gpu.Maxwell3D().state.shader_stages[stage_index]};
  697. u32 binding = device.GetBaseBindings(stage_index).shader_storage_buffer;
  698. for (const auto& entry : shader->GetShaderEntries().global_memory_entries) {
  699. const auto addr{cbufs.const_buffers[entry.GetCbufIndex()].address + entry.GetCbufOffset()};
  700. const auto gpu_addr{memory_manager.Read<u64>(addr)};
  701. const auto size{memory_manager.Read<u32>(addr + 8)};
  702. SetupGlobalMemory(binding++, entry, gpu_addr, size);
  703. }
  704. }
  705. void RasterizerOpenGL::SetupComputeGlobalMemory(const Shader& kernel) {
  706. auto& gpu{system.GPU()};
  707. auto& memory_manager{gpu.MemoryManager()};
  708. const auto cbufs{gpu.KeplerCompute().launch_description.const_buffer_config};
  709. u32 binding = 0;
  710. for (const auto& entry : kernel->GetShaderEntries().global_memory_entries) {
  711. const auto addr{cbufs[entry.GetCbufIndex()].Address() + entry.GetCbufOffset()};
  712. const auto gpu_addr{memory_manager.Read<u64>(addr)};
  713. const auto size{memory_manager.Read<u32>(addr + 8)};
  714. SetupGlobalMemory(binding++, entry, gpu_addr, size);
  715. }
  716. }
  717. void RasterizerOpenGL::SetupGlobalMemory(u32 binding, const GLShader::GlobalMemoryEntry& entry,
  718. GPUVAddr gpu_addr, std::size_t size) {
  719. const auto alignment{device.GetShaderStorageBufferAlignment()};
  720. const auto [ssbo, buffer_offset] =
  721. buffer_cache.UploadMemory(gpu_addr, size, alignment, entry.IsWritten());
  722. bind_ssbo_pushbuffer.Push(binding, ssbo, buffer_offset, static_cast<GLsizeiptr>(size));
  723. }
  724. void RasterizerOpenGL::SetupDrawTextures(std::size_t stage_index, const Shader& shader) {
  725. MICROPROFILE_SCOPE(OpenGL_Texture);
  726. const auto& maxwell3d = system.GPU().Maxwell3D();
  727. u32 binding = device.GetBaseBindings(stage_index).sampler;
  728. for (const auto& entry : shader->GetShaderEntries().samplers) {
  729. const auto shader_type = static_cast<Tegra::Engines::ShaderType>(stage_index);
  730. if (!entry.IsIndexed()) {
  731. const auto texture = GetTextureInfo(maxwell3d, entry, shader_type);
  732. SetupTexture(binding++, texture, entry);
  733. } else {
  734. for (std::size_t i = 0; i < entry.Size(); ++i) {
  735. const auto texture = GetTextureInfo(maxwell3d, entry, shader_type, i);
  736. SetupTexture(binding++, texture, entry);
  737. }
  738. }
  739. }
  740. }
  741. void RasterizerOpenGL::SetupComputeTextures(const Shader& kernel) {
  742. MICROPROFILE_SCOPE(OpenGL_Texture);
  743. const auto& compute = system.GPU().KeplerCompute();
  744. u32 binding = 0;
  745. for (const auto& entry : kernel->GetShaderEntries().samplers) {
  746. if (!entry.IsIndexed()) {
  747. const auto texture =
  748. GetTextureInfo(compute, entry, Tegra::Engines::ShaderType::Compute);
  749. SetupTexture(binding++, texture, entry);
  750. } else {
  751. for (std::size_t i = 0; i < entry.Size(); ++i) {
  752. const auto texture =
  753. GetTextureInfo(compute, entry, Tegra::Engines::ShaderType::Compute, i);
  754. SetupTexture(binding++, texture, entry);
  755. }
  756. }
  757. }
  758. }
  759. void RasterizerOpenGL::SetupTexture(u32 binding, const Tegra::Texture::FullTextureInfo& texture,
  760. const GLShader::SamplerEntry& entry) {
  761. const auto view = texture_cache.GetTextureSurface(texture.tic, entry);
  762. if (!view) {
  763. // Can occur when texture addr is null or its memory is unmapped/invalid
  764. state.samplers[binding] = 0;
  765. state.textures[binding] = 0;
  766. return;
  767. }
  768. state.textures[binding] = view->GetTexture();
  769. if (view->GetSurfaceParams().IsBuffer()) {
  770. return;
  771. }
  772. state.samplers[binding] = sampler_cache.GetSampler(texture.tsc);
  773. // Apply swizzle to textures that are not buffers.
  774. view->ApplySwizzle(texture.tic.x_source, texture.tic.y_source, texture.tic.z_source,
  775. texture.tic.w_source);
  776. }
  777. void RasterizerOpenGL::SetupDrawImages(std::size_t stage_index, const Shader& shader) {
  778. const auto& maxwell3d = system.GPU().Maxwell3D();
  779. u32 binding = device.GetBaseBindings(stage_index).image;
  780. for (const auto& entry : shader->GetShaderEntries().images) {
  781. const auto shader_type = static_cast<Tegra::Engines::ShaderType>(stage_index);
  782. const auto tic = GetTextureInfo(maxwell3d, entry, shader_type).tic;
  783. SetupImage(binding++, tic, entry);
  784. }
  785. }
  786. void RasterizerOpenGL::SetupComputeImages(const Shader& shader) {
  787. const auto& compute = system.GPU().KeplerCompute();
  788. u32 binding = 0;
  789. for (const auto& entry : shader->GetShaderEntries().images) {
  790. const auto tic = GetTextureInfo(compute, entry, Tegra::Engines::ShaderType::Compute).tic;
  791. SetupImage(binding++, tic, entry);
  792. }
  793. }
  794. void RasterizerOpenGL::SetupImage(u32 binding, const Tegra::Texture::TICEntry& tic,
  795. const GLShader::ImageEntry& entry) {
  796. const auto view = texture_cache.GetImageSurface(tic, entry);
  797. if (!view) {
  798. state.images[binding] = 0;
  799. return;
  800. }
  801. if (!tic.IsBuffer()) {
  802. view->ApplySwizzle(tic.x_source, tic.y_source, tic.z_source, tic.w_source);
  803. }
  804. if (entry.IsWritten()) {
  805. view->MarkAsModified(texture_cache.Tick());
  806. }
  807. state.images[binding] = view->GetTexture();
  808. }
  809. void RasterizerOpenGL::SyncViewport(OpenGLState& current_state) {
  810. const auto& regs = system.GPU().Maxwell3D().regs;
  811. const bool geometry_shaders_enabled =
  812. regs.IsShaderConfigEnabled(static_cast<size_t>(Maxwell::ShaderProgram::Geometry));
  813. const std::size_t viewport_count =
  814. geometry_shaders_enabled ? Tegra::Engines::Maxwell3D::Regs::NumViewports : 1;
  815. for (std::size_t i = 0; i < viewport_count; i++) {
  816. auto& viewport = current_state.viewports[i];
  817. const auto& src = regs.viewports[i];
  818. const Common::Rectangle<s32> viewport_rect{regs.viewport_transform[i].GetRect()};
  819. viewport.x = viewport_rect.left;
  820. viewport.y = viewport_rect.bottom;
  821. viewport.width = viewport_rect.GetWidth();
  822. viewport.height = viewport_rect.GetHeight();
  823. viewport.depth_range_far = src.depth_range_far;
  824. viewport.depth_range_near = src.depth_range_near;
  825. }
  826. state.depth_clamp.far_plane = regs.view_volume_clip_control.depth_clamp_far != 0;
  827. state.depth_clamp.near_plane = regs.view_volume_clip_control.depth_clamp_near != 0;
  828. bool flip_y = false;
  829. if (regs.viewport_transform[0].scale_y < 0.0) {
  830. flip_y = !flip_y;
  831. }
  832. if (regs.screen_y_control.y_negate != 0) {
  833. flip_y = !flip_y;
  834. }
  835. state.clip_control.origin = flip_y ? GL_UPPER_LEFT : GL_LOWER_LEFT;
  836. state.clip_control.depth_mode =
  837. regs.depth_mode == Tegra::Engines::Maxwell3D::Regs::DepthMode::ZeroToOne
  838. ? GL_ZERO_TO_ONE
  839. : GL_NEGATIVE_ONE_TO_ONE;
  840. }
  841. void RasterizerOpenGL::SyncClipEnabled(
  842. const std::array<bool, Maxwell::Regs::NumClipDistances>& clip_mask) {
  843. const auto& regs = system.GPU().Maxwell3D().regs;
  844. const std::array<bool, Maxwell::Regs::NumClipDistances> reg_state{
  845. regs.clip_distance_enabled.c0 != 0, regs.clip_distance_enabled.c1 != 0,
  846. regs.clip_distance_enabled.c2 != 0, regs.clip_distance_enabled.c3 != 0,
  847. regs.clip_distance_enabled.c4 != 0, regs.clip_distance_enabled.c5 != 0,
  848. regs.clip_distance_enabled.c6 != 0, regs.clip_distance_enabled.c7 != 0};
  849. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  850. state.clip_distance[i] = reg_state[i] && clip_mask[i];
  851. }
  852. }
  853. void RasterizerOpenGL::SyncClipCoef() {
  854. UNIMPLEMENTED();
  855. }
  856. void RasterizerOpenGL::SyncCullMode() {
  857. const auto& regs = system.GPU().Maxwell3D().regs;
  858. state.cull.enabled = regs.cull.enabled != 0;
  859. if (state.cull.enabled) {
  860. state.cull.mode = MaxwellToGL::CullFace(regs.cull.cull_face);
  861. }
  862. state.cull.front_face = MaxwellToGL::FrontFace(regs.cull.front_face);
  863. }
  864. void RasterizerOpenGL::SyncPrimitiveRestart() {
  865. const auto& regs = system.GPU().Maxwell3D().regs;
  866. state.primitive_restart.enabled = regs.primitive_restart.enabled;
  867. state.primitive_restart.index = regs.primitive_restart.index;
  868. }
  869. void RasterizerOpenGL::SyncDepthTestState() {
  870. const auto& regs = system.GPU().Maxwell3D().regs;
  871. state.depth.test_enabled = regs.depth_test_enable != 0;
  872. state.depth.write_mask = regs.depth_write_enabled ? GL_TRUE : GL_FALSE;
  873. if (!state.depth.test_enabled) {
  874. return;
  875. }
  876. state.depth.test_func = MaxwellToGL::ComparisonOp(regs.depth_test_func);
  877. }
  878. void RasterizerOpenGL::SyncStencilTestState() {
  879. auto& maxwell3d = system.GPU().Maxwell3D();
  880. const auto& regs = maxwell3d.regs;
  881. state.stencil.test_enabled = regs.stencil_enable != 0;
  882. if (!regs.stencil_enable) {
  883. return;
  884. }
  885. state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func);
  886. state.stencil.front.test_ref = regs.stencil_front_func_ref;
  887. state.stencil.front.test_mask = regs.stencil_front_func_mask;
  888. state.stencil.front.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_fail);
  889. state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail);
  890. state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass);
  891. state.stencil.front.write_mask = regs.stencil_front_mask;
  892. if (regs.stencil_two_side_enable) {
  893. state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
  894. state.stencil.back.test_ref = regs.stencil_back_func_ref;
  895. state.stencil.back.test_mask = regs.stencil_back_func_mask;
  896. state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
  897. state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
  898. state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
  899. state.stencil.back.write_mask = regs.stencil_back_mask;
  900. } else {
  901. state.stencil.back.test_func = GL_ALWAYS;
  902. state.stencil.back.test_ref = 0;
  903. state.stencil.back.test_mask = 0xFFFFFFFF;
  904. state.stencil.back.write_mask = 0xFFFFFFFF;
  905. state.stencil.back.action_stencil_fail = GL_KEEP;
  906. state.stencil.back.action_depth_fail = GL_KEEP;
  907. state.stencil.back.action_depth_pass = GL_KEEP;
  908. }
  909. }
  910. void RasterizerOpenGL::SyncRasterizeEnable(OpenGLState& current_state) {
  911. const auto& regs = system.GPU().Maxwell3D().regs;
  912. current_state.rasterizer_discard = regs.rasterize_enable == 0;
  913. }
  914. void RasterizerOpenGL::SyncColorMask() {
  915. auto& maxwell3d = system.GPU().Maxwell3D();
  916. const auto& regs = maxwell3d.regs;
  917. const std::size_t count =
  918. regs.independent_blend_enable ? Tegra::Engines::Maxwell3D::Regs::NumRenderTargets : 1;
  919. for (std::size_t i = 0; i < count; i++) {
  920. const auto& source = regs.color_mask[regs.color_mask_common ? 0 : i];
  921. auto& dest = state.color_mask[i];
  922. dest.red_enabled = (source.R == 0) ? GL_FALSE : GL_TRUE;
  923. dest.green_enabled = (source.G == 0) ? GL_FALSE : GL_TRUE;
  924. dest.blue_enabled = (source.B == 0) ? GL_FALSE : GL_TRUE;
  925. dest.alpha_enabled = (source.A == 0) ? GL_FALSE : GL_TRUE;
  926. }
  927. }
  928. void RasterizerOpenGL::SyncMultiSampleState() {
  929. const auto& regs = system.GPU().Maxwell3D().regs;
  930. state.multisample_control.alpha_to_coverage = regs.multisample_control.alpha_to_coverage != 0;
  931. state.multisample_control.alpha_to_one = regs.multisample_control.alpha_to_one != 0;
  932. }
  933. void RasterizerOpenGL::SyncFragmentColorClampState() {
  934. const auto& regs = system.GPU().Maxwell3D().regs;
  935. state.fragment_color_clamp.enabled = regs.frag_color_clamp != 0;
  936. }
  937. void RasterizerOpenGL::SyncBlendState() {
  938. auto& maxwell3d = system.GPU().Maxwell3D();
  939. const auto& regs = maxwell3d.regs;
  940. state.blend_color.red = regs.blend_color.r;
  941. state.blend_color.green = regs.blend_color.g;
  942. state.blend_color.blue = regs.blend_color.b;
  943. state.blend_color.alpha = regs.blend_color.a;
  944. state.independant_blend.enabled = regs.independent_blend_enable;
  945. if (!state.independant_blend.enabled) {
  946. auto& blend = state.blend[0];
  947. const auto& src = regs.blend;
  948. blend.enabled = src.enable[0] != 0;
  949. if (blend.enabled) {
  950. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  951. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  952. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  953. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  954. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  955. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  956. }
  957. for (std::size_t i = 1; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  958. state.blend[i].enabled = false;
  959. }
  960. return;
  961. }
  962. for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  963. auto& blend = state.blend[i];
  964. const auto& src = regs.independent_blend[i];
  965. blend.enabled = regs.blend.enable[i] != 0;
  966. if (!blend.enabled)
  967. continue;
  968. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  969. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  970. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  971. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  972. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  973. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  974. }
  975. }
  976. void RasterizerOpenGL::SyncLogicOpState() {
  977. const auto& regs = system.GPU().Maxwell3D().regs;
  978. state.logic_op.enabled = regs.logic_op.enable != 0;
  979. if (!state.logic_op.enabled)
  980. return;
  981. ASSERT_MSG(regs.blend.enable[0] == 0,
  982. "Blending and logic op can't be enabled at the same time.");
  983. state.logic_op.operation = MaxwellToGL::LogicOp(regs.logic_op.operation);
  984. }
  985. void RasterizerOpenGL::SyncScissorTest(OpenGLState& current_state) {
  986. const auto& regs = system.GPU().Maxwell3D().regs;
  987. const bool geometry_shaders_enabled =
  988. regs.IsShaderConfigEnabled(static_cast<size_t>(Maxwell::ShaderProgram::Geometry));
  989. const std::size_t viewport_count =
  990. geometry_shaders_enabled ? Tegra::Engines::Maxwell3D::Regs::NumViewports : 1;
  991. for (std::size_t i = 0; i < viewport_count; i++) {
  992. const auto& src = regs.scissor_test[i];
  993. auto& dst = current_state.viewports[i].scissor;
  994. dst.enabled = (src.enable != 0);
  995. if (dst.enabled == 0) {
  996. return;
  997. }
  998. const u32 width = src.max_x - src.min_x;
  999. const u32 height = src.max_y - src.min_y;
  1000. dst.x = src.min_x;
  1001. dst.y = src.min_y;
  1002. dst.width = width;
  1003. dst.height = height;
  1004. }
  1005. }
  1006. void RasterizerOpenGL::SyncTransformFeedback() {
  1007. const auto& regs = system.GPU().Maxwell3D().regs;
  1008. UNIMPLEMENTED_IF_MSG(regs.tfb_enabled != 0, "Transform feedbacks are not implemented");
  1009. }
  1010. void RasterizerOpenGL::SyncPointState() {
  1011. const auto& regs = system.GPU().Maxwell3D().regs;
  1012. // Limit the point size to 1 since nouveau sometimes sets a point size of 0 (and that's invalid
  1013. // in OpenGL).
  1014. oglEnable(GL_PROGRAM_POINT_SIZE, regs.vp_point_size.enable);
  1015. oglEnable(GL_POINT_SPRITE, regs.point_sprite_enable);
  1016. glPointSize(std::max(1.0f, regs.point_size));
  1017. }
  1018. void RasterizerOpenGL::SyncPolygonOffset() {
  1019. auto& maxwell3d = system.GPU().Maxwell3D();
  1020. const auto& regs = maxwell3d.regs;
  1021. state.polygon_offset.fill_enable = regs.polygon_offset_fill_enable != 0;
  1022. state.polygon_offset.line_enable = regs.polygon_offset_line_enable != 0;
  1023. state.polygon_offset.point_enable = regs.polygon_offset_point_enable != 0;
  1024. // Hardware divides polygon offset units by two
  1025. state.polygon_offset.units = regs.polygon_offset_units / 2.0f;
  1026. state.polygon_offset.factor = regs.polygon_offset_factor;
  1027. state.polygon_offset.clamp = regs.polygon_offset_clamp;
  1028. }
  1029. void RasterizerOpenGL::SyncAlphaTest() {
  1030. const auto& regs = system.GPU().Maxwell3D().regs;
  1031. UNIMPLEMENTED_IF_MSG(regs.alpha_test_enabled != 0 && regs.rt_control.count > 1,
  1032. "Alpha Testing is enabled with more than one rendertarget");
  1033. state.alpha_test.enabled = regs.alpha_test_enabled;
  1034. if (!state.alpha_test.enabled) {
  1035. return;
  1036. }
  1037. state.alpha_test.func = MaxwellToGL::ComparisonOp(regs.alpha_test_func);
  1038. state.alpha_test.ref = regs.alpha_test_ref;
  1039. }
  1040. } // namespace OpenGL