gl_rasterizer.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. // Copyright 2015 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <memory>
  7. #include <string>
  8. #include <string_view>
  9. #include <tuple>
  10. #include <utility>
  11. #include <glad/glad.h>
  12. #include "common/alignment.h"
  13. #include "common/assert.h"
  14. #include "common/logging/log.h"
  15. #include "common/math_util.h"
  16. #include "common/microprofile.h"
  17. #include "common/scope_exit.h"
  18. #include "core/core.h"
  19. #include "core/frontend/emu_window.h"
  20. #include "core/hle/kernel/process.h"
  21. #include "core/settings.h"
  22. #include "video_core/engines/maxwell_3d.h"
  23. #include "video_core/renderer_opengl/gl_rasterizer.h"
  24. #include "video_core/renderer_opengl/gl_shader_gen.h"
  25. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  26. #include "video_core/renderer_opengl/renderer_opengl.h"
  27. #include "video_core/video_core.h"
  28. namespace OpenGL {
  29. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  30. using PixelFormat = VideoCore::Surface::PixelFormat;
  31. using SurfaceType = VideoCore::Surface::SurfaceType;
  32. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Format Setup", MP_RGB(128, 128, 192));
  33. MICROPROFILE_DEFINE(OpenGL_VB, "OpenGL", "Vertex Buffer Setup", MP_RGB(128, 128, 192));
  34. MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192));
  35. MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192));
  36. MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192));
  37. MICROPROFILE_DEFINE(OpenGL_Texture, "OpenGL", "Texture Setup", MP_RGB(128, 128, 192));
  38. MICROPROFILE_DEFINE(OpenGL_Framebuffer, "OpenGL", "Framebuffer Setup", MP_RGB(128, 128, 192));
  39. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  40. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
  41. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
  42. MICROPROFILE_DEFINE(OpenGL_PrimitiveAssembly, "OpenGL", "Prim Asmbl", MP_RGB(255, 100, 100));
  43. struct DrawParameters {
  44. GLenum primitive_mode;
  45. GLsizei count;
  46. GLint current_instance;
  47. bool use_indexed;
  48. GLint vertex_first;
  49. GLenum index_format;
  50. GLint base_vertex;
  51. GLintptr index_buffer_offset;
  52. void DispatchDraw() const {
  53. if (use_indexed) {
  54. const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
  55. if (current_instance > 0) {
  56. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
  57. index_buffer_ptr, 1, base_vertex,
  58. current_instance);
  59. } else {
  60. glDrawElementsBaseVertex(primitive_mode, count, index_format, index_buffer_ptr,
  61. base_vertex);
  62. }
  63. } else {
  64. if (current_instance > 0) {
  65. glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, 1,
  66. current_instance);
  67. } else {
  68. glDrawArrays(primitive_mode, vertex_first, count);
  69. }
  70. }
  71. }
  72. };
  73. RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo& info)
  74. : emu_window{window}, screen_info{info}, buffer_cache(STREAM_BUFFER_SIZE) {
  75. // Create sampler objects
  76. for (std::size_t i = 0; i < texture_samplers.size(); ++i) {
  77. texture_samplers[i].Create();
  78. state.texture_units[i].sampler = texture_samplers[i].sampler.handle;
  79. }
  80. GLint ext_num;
  81. glGetIntegerv(GL_NUM_EXTENSIONS, &ext_num);
  82. for (GLint i = 0; i < ext_num; i++) {
  83. const std::string_view extension{
  84. reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i))};
  85. if (extension == "GL_ARB_direct_state_access") {
  86. has_ARB_direct_state_access = true;
  87. } else if (extension == "GL_ARB_multi_bind") {
  88. has_ARB_multi_bind = true;
  89. } else if (extension == "GL_ARB_separate_shader_objects") {
  90. has_ARB_separate_shader_objects = true;
  91. } else if (extension == "GL_ARB_vertex_attrib_binding") {
  92. has_ARB_vertex_attrib_binding = true;
  93. }
  94. }
  95. ASSERT_MSG(has_ARB_separate_shader_objects, "has_ARB_separate_shader_objects is unsupported");
  96. OpenGLState::ApplyDefaultState();
  97. // Clipping plane 0 is always enabled for PICA fixed clip plane z <= 0
  98. state.clip_distance[0] = true;
  99. // Create render framebuffer
  100. framebuffer.Create();
  101. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  102. state.draw.shader_program = 0;
  103. state.Apply();
  104. glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uniform_buffer_alignment);
  105. LOG_CRITICAL(Render_OpenGL, "Sync fixed function OpenGL state here!");
  106. }
  107. RasterizerOpenGL::~RasterizerOpenGL() {}
  108. void RasterizerOpenGL::SetupVertexFormat() {
  109. MICROPROFILE_SCOPE(OpenGL_VAO);
  110. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  111. const auto& regs = gpu.regs;
  112. auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
  113. auto& VAO = iter->second;
  114. if (is_cache_miss) {
  115. VAO.Create();
  116. state.draw.vertex_array = VAO.handle;
  117. state.Apply();
  118. // The index buffer binding is stored within the VAO. Stupid OpenGL, but easy to work
  119. // around.
  120. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer_cache.GetHandle());
  121. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  122. // Enables the first 16 vertex attributes always, as we don't know which ones are actually
  123. // used until shader time. Note, Tegra technically supports 32, but we're capping this to 16
  124. // for now to avoid OpenGL errors.
  125. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  126. // assume every shader uses them all.
  127. for (unsigned index = 0; index < 16; ++index) {
  128. const auto& attrib = regs.vertex_attrib_format[index];
  129. // Ignore invalid attributes.
  130. if (!attrib.IsValid())
  131. continue;
  132. const auto& buffer = regs.vertex_array[attrib.buffer];
  133. LOG_TRACE(HW_GPU,
  134. "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  135. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  136. attrib.offset.Value(), attrib.IsNormalized());
  137. ASSERT(buffer.IsEnabled());
  138. glEnableVertexAttribArray(index);
  139. if (attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::SignedInt ||
  140. attrib.type ==
  141. Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::UnsignedInt) {
  142. glVertexAttribIFormat(index, attrib.ComponentCount(),
  143. MaxwellToGL::VertexType(attrib), attrib.offset);
  144. } else {
  145. glVertexAttribFormat(index, attrib.ComponentCount(),
  146. MaxwellToGL::VertexType(attrib),
  147. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  148. }
  149. glVertexAttribBinding(index, attrib.buffer);
  150. }
  151. }
  152. state.draw.vertex_array = VAO.handle;
  153. state.Apply();
  154. }
  155. void RasterizerOpenGL::SetupVertexBuffer() {
  156. MICROPROFILE_SCOPE(OpenGL_VB);
  157. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  158. const auto& regs = gpu.regs;
  159. // Upload all guest vertex arrays sequentially to our buffer
  160. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  161. const auto& vertex_array = regs.vertex_array[index];
  162. if (!vertex_array.IsEnabled())
  163. continue;
  164. Tegra::GPUVAddr start = vertex_array.StartAddress();
  165. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  166. ASSERT(end > start);
  167. const u64 size = end - start + 1;
  168. const GLintptr vertex_buffer_offset = buffer_cache.UploadMemory(start, size);
  169. // Bind the vertex array to the buffer at the current offset.
  170. glBindVertexBuffer(index, buffer_cache.GetHandle(), vertex_buffer_offset,
  171. vertex_array.stride);
  172. if (regs.instanced_arrays.IsInstancingEnabled(index) && vertex_array.divisor != 0) {
  173. // Enable vertex buffer instancing with the specified divisor.
  174. glVertexBindingDivisor(index, vertex_array.divisor);
  175. } else {
  176. // Disable the vertex buffer instancing.
  177. glVertexBindingDivisor(index, 0);
  178. }
  179. }
  180. // Implicit set by glBindVertexBuffer. Stupid glstate handling...
  181. state.draw.vertex_buffer = buffer_cache.GetHandle();
  182. }
  183. DrawParameters RasterizerOpenGL::SetupDraw() {
  184. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  185. const auto& regs = gpu.regs;
  186. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  187. DrawParameters params{};
  188. params.current_instance = gpu.state.current_instance;
  189. if (regs.draw.topology == Maxwell::PrimitiveTopology::Quads) {
  190. MICROPROFILE_SCOPE(OpenGL_PrimitiveAssembly);
  191. params.use_indexed = true;
  192. params.primitive_mode = GL_TRIANGLES;
  193. if (is_indexed) {
  194. params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
  195. params.count = (regs.index_array.count / 4) * 6;
  196. params.index_buffer_offset = primitive_assembler.MakeQuadIndexed(
  197. regs.index_array.IndexStart(), regs.index_array.FormatSizeInBytes(),
  198. regs.index_array.count);
  199. params.base_vertex = static_cast<GLint>(regs.vb_element_base);
  200. } else {
  201. // MakeQuadArray always generates u32 indexes
  202. params.index_format = GL_UNSIGNED_INT;
  203. params.count = (regs.vertex_buffer.count / 4) * 6;
  204. params.index_buffer_offset =
  205. primitive_assembler.MakeQuadArray(regs.vertex_buffer.first, params.count);
  206. }
  207. return params;
  208. }
  209. params.use_indexed = is_indexed;
  210. params.primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
  211. if (is_indexed) {
  212. MICROPROFILE_SCOPE(OpenGL_Index);
  213. params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
  214. params.count = regs.index_array.count;
  215. params.index_buffer_offset =
  216. buffer_cache.UploadMemory(regs.index_array.IndexStart(), CalculateIndexBufferSize());
  217. params.base_vertex = static_cast<GLint>(regs.vb_element_base);
  218. } else {
  219. params.count = regs.vertex_buffer.count;
  220. params.vertex_first = regs.vertex_buffer.first;
  221. }
  222. return params;
  223. }
  224. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  225. MICROPROFILE_SCOPE(OpenGL_Shader);
  226. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  227. // Next available bindpoints to use when uploading the const buffers and textures to the GLSL
  228. // shaders. The constbuffer bindpoint starts after the shader stage configuration bind points.
  229. u32 current_constbuffer_bindpoint = Tegra::Engines::Maxwell3D::Regs::MaxShaderStage;
  230. u32 current_texture_bindpoint = 0;
  231. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  232. const auto& shader_config = gpu.regs.shader_config[index];
  233. const Maxwell::ShaderProgram program{static_cast<Maxwell::ShaderProgram>(index)};
  234. // Skip stages that are not enabled
  235. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  236. switch (program) {
  237. case Maxwell::ShaderProgram::Geometry:
  238. shader_program_manager->UseTrivialGeometryShader();
  239. break;
  240. }
  241. continue;
  242. }
  243. const std::size_t stage{index == 0 ? 0 : index - 1}; // Stage indices are 0 - 5
  244. GLShader::MaxwellUniformData ubo{};
  245. ubo.SetFromRegs(gpu.state.shader_stages[stage]);
  246. const GLintptr offset = buffer_cache.UploadHostMemory(
  247. &ubo, sizeof(ubo), static_cast<std::size_t>(uniform_buffer_alignment));
  248. // Bind the buffer
  249. glBindBufferRange(GL_UNIFORM_BUFFER, static_cast<GLuint>(stage), buffer_cache.GetHandle(),
  250. offset, static_cast<GLsizeiptr>(sizeof(ubo)));
  251. Shader shader{shader_cache.GetStageProgram(program)};
  252. switch (program) {
  253. case Maxwell::ShaderProgram::VertexA:
  254. case Maxwell::ShaderProgram::VertexB: {
  255. shader_program_manager->UseProgrammableVertexShader(
  256. shader->GetProgramHandle(primitive_mode));
  257. break;
  258. }
  259. case Maxwell::ShaderProgram::Geometry: {
  260. shader_program_manager->UseProgrammableGeometryShader(
  261. shader->GetProgramHandle(primitive_mode));
  262. break;
  263. }
  264. case Maxwell::ShaderProgram::Fragment: {
  265. shader_program_manager->UseProgrammableFragmentShader(
  266. shader->GetProgramHandle(primitive_mode));
  267. break;
  268. }
  269. default:
  270. LOG_CRITICAL(HW_GPU, "Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  271. shader_config.enable.Value(), shader_config.offset);
  272. UNREACHABLE();
  273. }
  274. // Configure the const buffers for this shader stage.
  275. current_constbuffer_bindpoint =
  276. SetupConstBuffers(static_cast<Maxwell::ShaderStage>(stage), shader, primitive_mode,
  277. current_constbuffer_bindpoint);
  278. // Configure the textures for this shader stage.
  279. current_texture_bindpoint = SetupTextures(static_cast<Maxwell::ShaderStage>(stage), shader,
  280. primitive_mode, current_texture_bindpoint);
  281. // When VertexA is enabled, we have dual vertex shaders
  282. if (program == Maxwell::ShaderProgram::VertexA) {
  283. // VertexB was combined with VertexA, so we skip the VertexB iteration
  284. index++;
  285. }
  286. }
  287. state.Apply();
  288. }
  289. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  290. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  291. std::size_t size = 0;
  292. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  293. if (!regs.vertex_array[index].IsEnabled())
  294. continue;
  295. const Tegra::GPUVAddr start = regs.vertex_array[index].StartAddress();
  296. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  297. ASSERT(end > start);
  298. size += end - start + 1;
  299. }
  300. return size;
  301. }
  302. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  303. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  304. return static_cast<std::size_t>(regs.index_array.count) *
  305. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  306. }
  307. bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
  308. accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
  309. DrawArrays();
  310. return true;
  311. }
  312. template <typename Map, typename Interval>
  313. static constexpr auto RangeFromInterval(Map& map, const Interval& interval) {
  314. return boost::make_iterator_range(map.equal_range(interval));
  315. }
  316. void RasterizerOpenGL::UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {
  317. const u64 page_start{addr >> Memory::PAGE_BITS};
  318. const u64 page_end{(addr + size + Memory::PAGE_SIZE - 1) >> Memory::PAGE_BITS};
  319. // Interval maps will erase segments if count reaches 0, so if delta is negative we have to
  320. // subtract after iterating
  321. const auto pages_interval = CachedPageMap::interval_type::right_open(page_start, page_end);
  322. if (delta > 0)
  323. cached_pages.add({pages_interval, delta});
  324. for (const auto& pair : RangeFromInterval(cached_pages, pages_interval)) {
  325. const auto interval = pair.first & pages_interval;
  326. const int count = pair.second;
  327. const VAddr interval_start_addr = boost::icl::first(interval) << Memory::PAGE_BITS;
  328. const VAddr interval_end_addr = boost::icl::last_next(interval) << Memory::PAGE_BITS;
  329. const u64 interval_size = interval_end_addr - interval_start_addr;
  330. if (delta > 0 && count == delta)
  331. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, true);
  332. else if (delta < 0 && count == -delta)
  333. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, false);
  334. else
  335. ASSERT(count >= 0);
  336. }
  337. if (delta < 0)
  338. cached_pages.add({pages_interval, delta});
  339. }
  340. void RasterizerOpenGL::ConfigureFramebuffers(bool using_color_fb, bool using_depth_fb,
  341. bool preserve_contents,
  342. std::optional<std::size_t> single_color_target) {
  343. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  344. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  345. Surface depth_surface;
  346. if (using_depth_fb) {
  347. depth_surface = res_cache.GetDepthBufferSurface(preserve_contents);
  348. }
  349. // TODO(bunnei): Figure out how the below register works. According to envytools, this should be
  350. // used to enable multiple render targets. However, it is left unset on all games that I have
  351. // tested.
  352. ASSERT_MSG(regs.rt_separate_frag_data == 0, "Unimplemented");
  353. // Bind the framebuffer surfaces
  354. state.draw.draw_framebuffer = framebuffer.handle;
  355. state.Apply();
  356. state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0;
  357. if (using_color_fb) {
  358. if (single_color_target) {
  359. // Used when just a single color attachment is enabled, e.g. for clearing a color buffer
  360. Surface color_surface =
  361. res_cache.GetColorBufferSurface(*single_color_target, preserve_contents);
  362. if (color_surface) {
  363. // Assume that a surface will be written to if it is used as a framebuffer, even if
  364. // the shader doesn't actually write to it.
  365. color_surface->MarkAsModified(true, res_cache);
  366. // Workaround for and issue in nvidia drivers
  367. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  368. state.framebuffer_srgb.enabled |= color_surface->GetSurfaceParams().srgb_conversion;
  369. }
  370. glFramebufferTexture2D(
  371. GL_DRAW_FRAMEBUFFER,
  372. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target), GL_TEXTURE_2D,
  373. color_surface != nullptr ? color_surface->Texture().handle : 0, 0);
  374. glDrawBuffer(GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target));
  375. } else {
  376. // Multiple color attachments are enabled
  377. std::array<GLenum, Maxwell::NumRenderTargets> buffers;
  378. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  379. Surface color_surface = res_cache.GetColorBufferSurface(index, preserve_contents);
  380. if (color_surface) {
  381. // Assume that a surface will be written to if it is used as a framebuffer, even
  382. // if the shader doesn't actually write to it.
  383. color_surface->MarkAsModified(true, res_cache);
  384. // Enable sRGB only for supported formats
  385. // Workaround for and issue in nvidia drivers
  386. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  387. state.framebuffer_srgb.enabled |=
  388. color_surface->GetSurfaceParams().srgb_conversion;
  389. }
  390. buffers[index] = GL_COLOR_ATTACHMENT0 + regs.rt_control.GetMap(index);
  391. glFramebufferTexture2D(
  392. GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index),
  393. GL_TEXTURE_2D, color_surface != nullptr ? color_surface->Texture().handle : 0,
  394. 0);
  395. }
  396. glDrawBuffers(regs.rt_control.count, buffers.data());
  397. }
  398. } else {
  399. // No color attachments are enabled - zero out all of them
  400. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  401. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
  402. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index), GL_TEXTURE_2D,
  403. 0, 0);
  404. }
  405. glDrawBuffer(GL_NONE);
  406. }
  407. if (depth_surface) {
  408. // Assume that a surface will be written to if it is used as a framebuffer, even if
  409. // the shader doesn't actually write to it.
  410. depth_surface->MarkAsModified(true, res_cache);
  411. if (regs.stencil_enable) {
  412. // Attach both depth and stencil
  413. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
  414. depth_surface->Texture().handle, 0);
  415. } else {
  416. // Attach depth
  417. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
  418. depth_surface->Texture().handle, 0);
  419. // Clear stencil attachment
  420. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
  421. }
  422. } else {
  423. // Clear both depth and stencil attachment
  424. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0,
  425. 0);
  426. }
  427. SyncViewport();
  428. state.Apply();
  429. }
  430. void RasterizerOpenGL::Clear() {
  431. const auto prev_state{state};
  432. SCOPE_EXIT({ prev_state.Apply(); });
  433. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  434. bool use_color{};
  435. bool use_depth{};
  436. bool use_stencil{};
  437. OpenGLState clear_state;
  438. clear_state.draw.draw_framebuffer = framebuffer.handle;
  439. clear_state.color_mask.red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
  440. clear_state.color_mask.green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
  441. clear_state.color_mask.blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
  442. clear_state.color_mask.alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
  443. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  444. regs.clear_buffers.A) {
  445. use_color = true;
  446. }
  447. if (regs.clear_buffers.Z) {
  448. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  449. use_depth = true;
  450. // Always enable the depth write when clearing the depth buffer. The depth write mask is
  451. // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to true.
  452. clear_state.depth.test_enabled = true;
  453. clear_state.depth.test_func = GL_ALWAYS;
  454. }
  455. if (regs.clear_buffers.S) {
  456. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear stencil but buffer is not enabled!");
  457. use_stencil = true;
  458. clear_state.stencil.test_enabled = true;
  459. }
  460. if (!use_color && !use_depth && !use_stencil) {
  461. // No color surface nor depth/stencil surface are enabled
  462. return;
  463. }
  464. ScopeAcquireGLContext acquire_context{emu_window};
  465. ConfigureFramebuffers(use_color, use_depth || use_stencil, false,
  466. regs.clear_buffers.RT.Value());
  467. // Copy the sRGB setting to the clear state to avoid problem with
  468. // specific driver implementations
  469. clear_state.framebuffer_srgb.enabled = state.framebuffer_srgb.enabled;
  470. clear_state.Apply();
  471. if (use_color) {
  472. glClearBufferfv(GL_COLOR, regs.clear_buffers.RT, regs.clear_color);
  473. }
  474. if (use_depth && use_stencil) {
  475. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  476. } else if (use_depth) {
  477. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  478. } else if (use_stencil) {
  479. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  480. }
  481. }
  482. void RasterizerOpenGL::DrawArrays() {
  483. if (accelerate_draw == AccelDraw::Disabled)
  484. return;
  485. MICROPROFILE_SCOPE(OpenGL_Drawing);
  486. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  487. const auto& regs = gpu.regs;
  488. ScopeAcquireGLContext acquire_context{emu_window};
  489. ConfigureFramebuffers();
  490. SyncDepthTestState();
  491. SyncStencilTestState();
  492. SyncBlendState();
  493. SyncLogicOpState();
  494. SyncCullMode();
  495. SyncPrimitiveRestart();
  496. SyncDepthRange();
  497. SyncScissorTest();
  498. // Alpha Testing is synced on shaders.
  499. SyncTransformFeedback();
  500. SyncPointState();
  501. CheckAlphaTests();
  502. // TODO(bunnei): Sync framebuffer_scale uniform here
  503. // TODO(bunnei): Sync scissorbox uniform(s) here
  504. // Draw the vertex batch
  505. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  506. state.draw.vertex_buffer = buffer_cache.GetHandle();
  507. state.Apply();
  508. std::size_t buffer_size = CalculateVertexArraysSize();
  509. // Add space for index buffer (keeping in mind non-core primitives)
  510. switch (regs.draw.topology) {
  511. case Maxwell::PrimitiveTopology::Quads:
  512. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) +
  513. primitive_assembler.CalculateQuadSize(regs.vertex_buffer.count);
  514. break;
  515. default:
  516. if (is_indexed) {
  517. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) + CalculateIndexBufferSize();
  518. }
  519. break;
  520. }
  521. // Uniform space for the 5 shader stages
  522. buffer_size =
  523. Common::AlignUp<std::size_t>(buffer_size, 4) +
  524. (sizeof(GLShader::MaxwellUniformData) + uniform_buffer_alignment) * Maxwell::MaxShaderStage;
  525. // Add space for at least 18 constant buffers
  526. buffer_size += Maxwell::MaxConstBuffers * (MaxConstbufferSize + uniform_buffer_alignment);
  527. buffer_cache.Map(buffer_size);
  528. SetupVertexFormat();
  529. SetupVertexBuffer();
  530. DrawParameters params = SetupDraw();
  531. SetupShaders(params.primitive_mode);
  532. buffer_cache.Unmap();
  533. shader_program_manager->ApplyTo(state);
  534. state.Apply();
  535. // Execute draw call
  536. params.DispatchDraw();
  537. // Disable scissor test
  538. state.scissor.enabled = false;
  539. accelerate_draw = AccelDraw::Disabled;
  540. // Unbind textures for potential future use as framebuffer attachments
  541. for (auto& texture_unit : state.texture_units) {
  542. texture_unit.Unbind();
  543. }
  544. state.Apply();
  545. }
  546. void RasterizerOpenGL::FlushAll() {}
  547. void RasterizerOpenGL::FlushRegion(VAddr addr, u64 size) {
  548. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  549. if (Settings::values.use_accurate_gpu_emulation) {
  550. // Only flush if use_accurate_gpu_emulation is enabled, as it incurs a performance hit
  551. res_cache.FlushRegion(addr, size);
  552. }
  553. }
  554. void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size) {
  555. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  556. res_cache.InvalidateRegion(addr, size);
  557. shader_cache.InvalidateRegion(addr, size);
  558. buffer_cache.InvalidateRegion(addr, size);
  559. }
  560. void RasterizerOpenGL::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  561. FlushRegion(addr, size);
  562. InvalidateRegion(addr, size);
  563. }
  564. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  565. const Tegra::Engines::Fermi2D::Regs::Surface& dst) {
  566. MICROPROFILE_SCOPE(OpenGL_Blits);
  567. if (Settings::values.use_accurate_gpu_emulation) {
  568. // Skip the accelerated copy and perform a slow but more accurate copy
  569. return false;
  570. }
  571. res_cache.FermiCopySurface(src, dst);
  572. return true;
  573. }
  574. bool RasterizerOpenGL::AccelerateFill(const void* config) {
  575. UNREACHABLE();
  576. return true;
  577. }
  578. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  579. VAddr framebuffer_addr, u32 pixel_stride) {
  580. if (!framebuffer_addr) {
  581. return {};
  582. }
  583. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  584. const auto& surface{res_cache.TryFindFramebufferSurface(framebuffer_addr)};
  585. if (!surface) {
  586. return {};
  587. }
  588. // Verify that the cached surface is the same size and format as the requested framebuffer
  589. const auto& params{surface->GetSurfaceParams()};
  590. const auto& pixel_format{
  591. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  592. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  593. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  594. ASSERT_MSG(params.pixel_format == pixel_format, "Framebuffer pixel_format is different");
  595. screen_info.display_texture = surface->Texture().handle;
  596. return true;
  597. }
  598. void RasterizerOpenGL::SamplerInfo::Create() {
  599. sampler.Create();
  600. mag_filter = min_filter = Tegra::Texture::TextureFilter::Linear;
  601. wrap_u = wrap_v = wrap_p = Tegra::Texture::WrapMode::Wrap;
  602. uses_depth_compare = false;
  603. depth_compare_func = Tegra::Texture::DepthCompareFunc::Never;
  604. // default is GL_LINEAR_MIPMAP_LINEAR
  605. glSamplerParameteri(sampler.handle, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  606. // Other attributes have correct defaults
  607. glSamplerParameteri(sampler.handle, GL_TEXTURE_COMPARE_FUNC, GL_NEVER);
  608. }
  609. void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntry& config) {
  610. const GLuint s = sampler.handle;
  611. if (mag_filter != config.mag_filter) {
  612. mag_filter = config.mag_filter;
  613. glSamplerParameteri(
  614. s, GL_TEXTURE_MAG_FILTER,
  615. MaxwellToGL::TextureFilterMode(mag_filter, Tegra::Texture::TextureMipmapFilter::None));
  616. }
  617. if (min_filter != config.min_filter || mip_filter != config.mip_filter) {
  618. min_filter = config.min_filter;
  619. mip_filter = config.mip_filter;
  620. glSamplerParameteri(s, GL_TEXTURE_MIN_FILTER,
  621. MaxwellToGL::TextureFilterMode(min_filter, mip_filter));
  622. }
  623. if (wrap_u != config.wrap_u) {
  624. wrap_u = config.wrap_u;
  625. glSamplerParameteri(s, GL_TEXTURE_WRAP_S, MaxwellToGL::WrapMode(wrap_u));
  626. }
  627. if (wrap_v != config.wrap_v) {
  628. wrap_v = config.wrap_v;
  629. glSamplerParameteri(s, GL_TEXTURE_WRAP_T, MaxwellToGL::WrapMode(wrap_v));
  630. }
  631. if (wrap_p != config.wrap_p) {
  632. wrap_p = config.wrap_p;
  633. glSamplerParameteri(s, GL_TEXTURE_WRAP_R, MaxwellToGL::WrapMode(wrap_p));
  634. }
  635. if (uses_depth_compare != (config.depth_compare_enabled == 1)) {
  636. uses_depth_compare = (config.depth_compare_enabled == 1);
  637. if (uses_depth_compare) {
  638. glSamplerParameteri(s, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  639. } else {
  640. glSamplerParameteri(s, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  641. }
  642. }
  643. if (depth_compare_func != config.depth_compare_func) {
  644. depth_compare_func = config.depth_compare_func;
  645. glSamplerParameteri(s, GL_TEXTURE_COMPARE_FUNC,
  646. MaxwellToGL::DepthCompareFunc(depth_compare_func));
  647. }
  648. if (wrap_u == Tegra::Texture::WrapMode::Border || wrap_v == Tegra::Texture::WrapMode::Border ||
  649. wrap_p == Tegra::Texture::WrapMode::Border) {
  650. const GLvec4 new_border_color = {{config.border_color_r, config.border_color_g,
  651. config.border_color_b, config.border_color_a}};
  652. if (border_color != new_border_color) {
  653. border_color = new_border_color;
  654. glSamplerParameterfv(s, GL_TEXTURE_BORDER_COLOR, border_color.data());
  655. }
  656. }
  657. }
  658. u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shader,
  659. GLenum primitive_mode, u32 current_bindpoint) {
  660. MICROPROFILE_SCOPE(OpenGL_UBO);
  661. const auto& gpu = Core::System::GetInstance().GPU();
  662. const auto& maxwell3d = gpu.Maxwell3D();
  663. const auto& shader_stage = maxwell3d.state.shader_stages[static_cast<std::size_t>(stage)];
  664. const auto& entries = shader->GetShaderEntries().const_buffer_entries;
  665. constexpr u64 max_binds = Tegra::Engines::Maxwell3D::Regs::MaxConstBuffers;
  666. std::array<GLuint, max_binds> bind_buffers;
  667. std::array<GLintptr, max_binds> bind_offsets;
  668. std::array<GLsizeiptr, max_binds> bind_sizes;
  669. ASSERT_MSG(entries.size() <= max_binds, "Exceeded expected number of binding points.");
  670. // Upload only the enabled buffers from the 16 constbuffers of each shader stage
  671. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  672. const auto& used_buffer = entries[bindpoint];
  673. const auto& buffer = shader_stage.const_buffers[used_buffer.GetIndex()];
  674. if (!buffer.enabled) {
  675. // With disabled buffers set values as zero to unbind them
  676. bind_buffers[bindpoint] = 0;
  677. bind_offsets[bindpoint] = 0;
  678. bind_sizes[bindpoint] = 0;
  679. continue;
  680. }
  681. std::size_t size = 0;
  682. if (used_buffer.IsIndirect()) {
  683. // Buffer is accessed indirectly, so upload the entire thing
  684. size = buffer.size;
  685. if (size > MaxConstbufferSize) {
  686. LOG_CRITICAL(HW_GPU, "indirect constbuffer size {} exceeds maximum {}", size,
  687. MaxConstbufferSize);
  688. size = MaxConstbufferSize;
  689. }
  690. } else {
  691. // Buffer is accessed directly, upload just what we use
  692. size = used_buffer.GetSize() * sizeof(float);
  693. }
  694. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  695. // UBO alignment requirements.
  696. size = Common::AlignUp(size, sizeof(GLvec4));
  697. ASSERT_MSG(size <= MaxConstbufferSize, "Constbuffer too big");
  698. GLintptr const_buffer_offset = buffer_cache.UploadMemory(
  699. buffer.address, size, static_cast<std::size_t>(uniform_buffer_alignment));
  700. // Now configure the bindpoint of the buffer inside the shader
  701. glUniformBlockBinding(shader->GetProgramHandle(primitive_mode),
  702. shader->GetProgramResourceIndex(used_buffer),
  703. current_bindpoint + bindpoint);
  704. // Prepare values for multibind
  705. bind_buffers[bindpoint] = buffer_cache.GetHandle();
  706. bind_offsets[bindpoint] = const_buffer_offset;
  707. bind_sizes[bindpoint] = size;
  708. }
  709. glBindBuffersRange(GL_UNIFORM_BUFFER, current_bindpoint, static_cast<GLsizei>(entries.size()),
  710. bind_buffers.data(), bind_offsets.data(), bind_sizes.data());
  711. return current_bindpoint + static_cast<u32>(entries.size());
  712. }
  713. u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, Shader& shader,
  714. GLenum primitive_mode, u32 current_unit) {
  715. MICROPROFILE_SCOPE(OpenGL_Texture);
  716. const auto& gpu = Core::System::GetInstance().GPU();
  717. const auto& maxwell3d = gpu.Maxwell3D();
  718. const auto& entries = shader->GetShaderEntries().texture_samplers;
  719. ASSERT_MSG(current_unit + entries.size() <= std::size(state.texture_units),
  720. "Exceeded the number of active textures.");
  721. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  722. const auto& entry = entries[bindpoint];
  723. const u32 current_bindpoint = current_unit + bindpoint;
  724. // Bind the uniform to the sampler.
  725. glProgramUniform1i(shader->GetProgramHandle(primitive_mode),
  726. shader->GetUniformLocation(entry), current_bindpoint);
  727. const auto texture = maxwell3d.GetStageTexture(entry.GetStage(), entry.GetOffset());
  728. if (!texture.enabled) {
  729. state.texture_units[current_bindpoint].texture = 0;
  730. continue;
  731. }
  732. texture_samplers[current_bindpoint].SyncWithConfig(texture.tsc);
  733. Surface surface = res_cache.GetTextureSurface(texture, entry);
  734. if (surface != nullptr) {
  735. state.texture_units[current_bindpoint].texture = surface->Texture().handle;
  736. state.texture_units[current_bindpoint].target = surface->Target();
  737. state.texture_units[current_bindpoint].swizzle.r =
  738. MaxwellToGL::SwizzleSource(texture.tic.x_source);
  739. state.texture_units[current_bindpoint].swizzle.g =
  740. MaxwellToGL::SwizzleSource(texture.tic.y_source);
  741. state.texture_units[current_bindpoint].swizzle.b =
  742. MaxwellToGL::SwizzleSource(texture.tic.z_source);
  743. state.texture_units[current_bindpoint].swizzle.a =
  744. MaxwellToGL::SwizzleSource(texture.tic.w_source);
  745. } else {
  746. // Can occur when texture addr is null or its memory is unmapped/invalid
  747. state.texture_units[current_bindpoint].texture = 0;
  748. }
  749. }
  750. return current_unit + static_cast<u32>(entries.size());
  751. }
  752. void RasterizerOpenGL::SyncViewport() {
  753. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  754. const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[0].GetRect()};
  755. state.viewport.x = viewport_rect.left;
  756. state.viewport.y = viewport_rect.bottom;
  757. state.viewport.width = static_cast<GLsizei>(viewport_rect.GetWidth());
  758. state.viewport.height = static_cast<GLsizei>(viewport_rect.GetHeight());
  759. }
  760. void RasterizerOpenGL::SyncClipEnabled() {
  761. UNREACHABLE();
  762. }
  763. void RasterizerOpenGL::SyncClipCoef() {
  764. UNREACHABLE();
  765. }
  766. void RasterizerOpenGL::SyncCullMode() {
  767. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  768. state.cull.enabled = regs.cull.enabled != 0;
  769. if (state.cull.enabled) {
  770. state.cull.front_face = MaxwellToGL::FrontFace(regs.cull.front_face);
  771. state.cull.mode = MaxwellToGL::CullFace(regs.cull.cull_face);
  772. const bool flip_triangles{regs.screen_y_control.triangle_rast_flip == 0 ||
  773. regs.viewport_transform[0].scale_y < 0.0f};
  774. // If the GPU is configured to flip the rasterized triangles, then we need to flip the
  775. // notion of front and back. Note: We flip the triangles when the value of the register is 0
  776. // because OpenGL already does it for us.
  777. if (flip_triangles) {
  778. if (state.cull.front_face == GL_CCW)
  779. state.cull.front_face = GL_CW;
  780. else if (state.cull.front_face == GL_CW)
  781. state.cull.front_face = GL_CCW;
  782. }
  783. }
  784. }
  785. void RasterizerOpenGL::SyncPrimitiveRestart() {
  786. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  787. state.primitive_restart.enabled = regs.primitive_restart.enabled;
  788. state.primitive_restart.index = regs.primitive_restart.index;
  789. }
  790. void RasterizerOpenGL::SyncDepthRange() {
  791. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  792. state.depth.depth_range_near = regs.viewport->depth_range_near;
  793. state.depth.depth_range_far = regs.viewport->depth_range_far;
  794. }
  795. void RasterizerOpenGL::SyncDepthTestState() {
  796. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  797. state.depth.test_enabled = regs.depth_test_enable != 0;
  798. state.depth.write_mask = regs.depth_write_enabled ? GL_TRUE : GL_FALSE;
  799. if (!state.depth.test_enabled)
  800. return;
  801. state.depth.test_func = MaxwellToGL::ComparisonOp(regs.depth_test_func);
  802. }
  803. void RasterizerOpenGL::SyncStencilTestState() {
  804. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  805. state.stencil.test_enabled = regs.stencil_enable != 0;
  806. if (!regs.stencil_enable) {
  807. return;
  808. }
  809. // TODO(bunnei): Verify behavior when this is not set
  810. ASSERT(regs.stencil_two_side_enable);
  811. state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func);
  812. state.stencil.front.test_ref = regs.stencil_front_func_ref;
  813. state.stencil.front.test_mask = regs.stencil_front_func_mask;
  814. state.stencil.front.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_fail);
  815. state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail);
  816. state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass);
  817. state.stencil.front.write_mask = regs.stencil_front_mask;
  818. state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
  819. state.stencil.back.test_ref = regs.stencil_back_func_ref;
  820. state.stencil.back.test_mask = regs.stencil_back_func_mask;
  821. state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
  822. state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
  823. state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
  824. state.stencil.back.write_mask = regs.stencil_back_mask;
  825. }
  826. void RasterizerOpenGL::SyncBlendState() {
  827. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  828. // TODO(Subv): Support more than just render target 0.
  829. state.blend.enabled = regs.blend.enable[0] != 0;
  830. if (!state.blend.enabled)
  831. return;
  832. ASSERT_MSG(regs.logic_op.enable == 0,
  833. "Blending and logic op can't be enabled at the same time.");
  834. ASSERT_MSG(regs.independent_blend_enable == 1, "Only independent blending is implemented");
  835. ASSERT_MSG(!regs.independent_blend[0].separate_alpha, "Unimplemented");
  836. state.blend.rgb_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_rgb);
  837. state.blend.src_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_rgb);
  838. state.blend.dst_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_rgb);
  839. state.blend.a_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_a);
  840. state.blend.src_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_a);
  841. state.blend.dst_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_a);
  842. }
  843. void RasterizerOpenGL::SyncLogicOpState() {
  844. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  845. // TODO(Subv): Support more than just render target 0.
  846. state.logic_op.enabled = regs.logic_op.enable != 0;
  847. if (!state.logic_op.enabled)
  848. return;
  849. ASSERT_MSG(regs.blend.enable[0] == 0,
  850. "Blending and logic op can't be enabled at the same time.");
  851. state.logic_op.operation = MaxwellToGL::LogicOp(regs.logic_op.operation);
  852. }
  853. void RasterizerOpenGL::SyncScissorTest() {
  854. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  855. state.scissor.enabled = (regs.scissor_test.enable != 0);
  856. // TODO(Blinkhawk): Figure if the hardware supports scissor testing per viewport and how it's
  857. // implemented.
  858. if (regs.scissor_test.enable != 0) {
  859. const u32 width = regs.scissor_test.max_x - regs.scissor_test.min_x;
  860. const u32 height = regs.scissor_test.max_y - regs.scissor_test.min_y;
  861. state.scissor.x = regs.scissor_test.min_x;
  862. state.scissor.y = regs.scissor_test.min_y;
  863. state.scissor.width = width;
  864. state.scissor.height = height;
  865. }
  866. }
  867. void RasterizerOpenGL::SyncTransformFeedback() {
  868. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  869. if (regs.tfb_enabled != 0) {
  870. LOG_CRITICAL(Render_OpenGL, "Transform feedbacks are not implemented");
  871. UNREACHABLE();
  872. }
  873. }
  874. void RasterizerOpenGL::SyncPointState() {
  875. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  876. // TODO(Rodrigo): Most games do not set a point size. I think this is a case of a
  877. // register carrying a default value. For now, if the point size is zero, assume it's
  878. // OpenGL's default (1).
  879. state.point.size = regs.point_size == 0 ? 1 : regs.point_size;
  880. }
  881. void RasterizerOpenGL::CheckAlphaTests() {
  882. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  883. if (regs.alpha_test_enabled != 0 && regs.rt_control.count > 1) {
  884. LOG_CRITICAL(
  885. Render_OpenGL,
  886. "Alpha Testing is enabled with Multiple Render Targets, this behavior is undefined.");
  887. UNREACHABLE();
  888. }
  889. }
  890. } // namespace OpenGL