gl_rasterizer.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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/hle/kernel/process.h"
  20. #include "core/settings.h"
  21. #include "video_core/engines/maxwell_3d.h"
  22. #include "video_core/renderer_opengl/gl_rasterizer.h"
  23. #include "video_core/renderer_opengl/gl_shader_cache.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. namespace OpenGL {
  28. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  29. using PixelFormat = VideoCore::Surface::PixelFormat;
  30. using SurfaceType = VideoCore::Surface::SurfaceType;
  31. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Format Setup", MP_RGB(128, 128, 192));
  32. MICROPROFILE_DEFINE(OpenGL_VB, "OpenGL", "Vertex Buffer Setup", MP_RGB(128, 128, 192));
  33. MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192));
  34. MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192));
  35. MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192));
  36. MICROPROFILE_DEFINE(OpenGL_Texture, "OpenGL", "Texture Setup", MP_RGB(128, 128, 192));
  37. MICROPROFILE_DEFINE(OpenGL_Framebuffer, "OpenGL", "Framebuffer Setup", MP_RGB(128, 128, 192));
  38. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  39. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
  40. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
  41. MICROPROFILE_DEFINE(OpenGL_PrimitiveAssembly, "OpenGL", "Prim Asmbl", MP_RGB(255, 100, 100));
  42. struct DrawParameters {
  43. GLenum primitive_mode;
  44. GLsizei count;
  45. GLint current_instance;
  46. bool use_indexed;
  47. GLint vertex_first;
  48. GLenum index_format;
  49. GLint base_vertex;
  50. GLintptr index_buffer_offset;
  51. void DispatchDraw() const {
  52. if (use_indexed) {
  53. const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
  54. if (current_instance > 0) {
  55. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
  56. index_buffer_ptr, 1, base_vertex,
  57. current_instance);
  58. } else {
  59. glDrawElementsBaseVertex(primitive_mode, count, index_format, index_buffer_ptr,
  60. base_vertex);
  61. }
  62. } else {
  63. if (current_instance > 0) {
  64. glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, 1,
  65. current_instance);
  66. } else {
  67. glDrawArrays(primitive_mode, vertex_first, count);
  68. }
  69. }
  70. }
  71. };
  72. struct FramebufferCacheKey {
  73. bool is_single_buffer = false;
  74. bool stencil_enable = false;
  75. std::array<GLenum, Maxwell::NumRenderTargets> color_attachments{};
  76. std::array<GLuint, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets> colors{};
  77. u32 colors_count = 0;
  78. GLuint zeta = 0;
  79. auto Tie() const {
  80. return std::tie(is_single_buffer, stencil_enable, color_attachments, colors, colors_count,
  81. zeta);
  82. }
  83. bool operator<(const FramebufferCacheKey& rhs) const {
  84. return Tie() < rhs.Tie();
  85. }
  86. };
  87. RasterizerOpenGL::RasterizerOpenGL(Core::System& system, ScreenInfo& info)
  88. : res_cache{*this}, shader_cache{*this, system}, global_cache{*this}, system{system},
  89. screen_info{info}, buffer_cache(*this, STREAM_BUFFER_SIZE) {
  90. // Create sampler objects
  91. for (std::size_t i = 0; i < texture_samplers.size(); ++i) {
  92. texture_samplers[i].Create();
  93. state.texture_units[i].sampler = texture_samplers[i].sampler.handle;
  94. }
  95. OpenGLState::ApplyDefaultState();
  96. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  97. state.draw.shader_program = 0;
  98. state.Apply();
  99. glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uniform_buffer_alignment);
  100. LOG_DEBUG(Render_OpenGL, "Sync fixed function OpenGL state here");
  101. CheckExtensions();
  102. }
  103. RasterizerOpenGL::~RasterizerOpenGL() {}
  104. void RasterizerOpenGL::CheckExtensions() {
  105. if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
  106. LOG_WARNING(
  107. Render_OpenGL,
  108. "Anisotropic filter is not supported! This can cause graphical issues in some games.");
  109. }
  110. if (!GLAD_GL_ARB_buffer_storage) {
  111. LOG_WARNING(
  112. Render_OpenGL,
  113. "Buffer storage control is not supported! This can cause performance degradation.");
  114. }
  115. }
  116. GLuint RasterizerOpenGL::SetupVertexFormat() {
  117. auto& gpu = system.GPU().Maxwell3D();
  118. const auto& regs = gpu.regs;
  119. if (!gpu.dirty_flags.vertex_attrib_format) {
  120. return state.draw.vertex_array;
  121. }
  122. gpu.dirty_flags.vertex_attrib_format = false;
  123. MICROPROFILE_SCOPE(OpenGL_VAO);
  124. auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
  125. auto& vao_entry = iter->second;
  126. if (is_cache_miss) {
  127. vao_entry.Create();
  128. const GLuint vao = vao_entry.handle;
  129. // Eventhough we are using DSA to create this vertex array, there is a bug on Intel's blob
  130. // that fails to properly create the vertex array if it's not bound even after creating it
  131. // with glCreateVertexArrays
  132. state.draw.vertex_array = vao;
  133. state.ApplyVertexArrayState();
  134. glVertexArrayElementBuffer(vao, buffer_cache.GetHandle());
  135. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  136. // Enables the first 16 vertex attributes always, as we don't know which ones are actually
  137. // used until shader time. Note, Tegra technically supports 32, but we're capping this to 16
  138. // for now to avoid OpenGL errors.
  139. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  140. // assume every shader uses them all.
  141. for (u32 index = 0; index < 16; ++index) {
  142. const auto& attrib = regs.vertex_attrib_format[index];
  143. // Ignore invalid attributes.
  144. if (!attrib.IsValid())
  145. continue;
  146. const auto& buffer = regs.vertex_array[attrib.buffer];
  147. LOG_TRACE(Render_OpenGL,
  148. "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  149. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  150. attrib.offset.Value(), attrib.IsNormalized());
  151. ASSERT(buffer.IsEnabled());
  152. glEnableVertexArrayAttrib(vao, index);
  153. if (attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::SignedInt ||
  154. attrib.type ==
  155. Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::UnsignedInt) {
  156. glVertexArrayAttribIFormat(vao, index, attrib.ComponentCount(),
  157. MaxwellToGL::VertexType(attrib), attrib.offset);
  158. } else {
  159. glVertexArrayAttribFormat(
  160. vao, index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  161. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  162. }
  163. glVertexArrayAttribBinding(vao, index, attrib.buffer);
  164. }
  165. }
  166. // Rebinding the VAO invalidates the vertex buffer bindings.
  167. gpu.dirty_flags.vertex_array.set();
  168. state.draw.vertex_array = vao_entry.handle;
  169. return vao_entry.handle;
  170. }
  171. void RasterizerOpenGL::SetupVertexBuffer(GLuint vao) {
  172. auto& gpu = system.GPU().Maxwell3D();
  173. const auto& regs = gpu.regs;
  174. if (gpu.dirty_flags.vertex_array.none())
  175. return;
  176. MICROPROFILE_SCOPE(OpenGL_VB);
  177. // Upload all guest vertex arrays sequentially to our buffer
  178. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  179. if (!gpu.dirty_flags.vertex_array[index])
  180. continue;
  181. const auto& vertex_array = regs.vertex_array[index];
  182. if (!vertex_array.IsEnabled())
  183. continue;
  184. const GPUVAddr start = vertex_array.StartAddress();
  185. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  186. ASSERT(end > start);
  187. const u64 size = end - start + 1;
  188. const GLintptr vertex_buffer_offset = buffer_cache.UploadMemory(start, size);
  189. // Bind the vertex array to the buffer at the current offset.
  190. glVertexArrayVertexBuffer(vao, index, buffer_cache.GetHandle(), vertex_buffer_offset,
  191. vertex_array.stride);
  192. if (regs.instanced_arrays.IsInstancingEnabled(index) && vertex_array.divisor != 0) {
  193. // Enable vertex buffer instancing with the specified divisor.
  194. glVertexArrayBindingDivisor(vao, index, vertex_array.divisor);
  195. } else {
  196. // Disable the vertex buffer instancing.
  197. glVertexArrayBindingDivisor(vao, index, 0);
  198. }
  199. }
  200. gpu.dirty_flags.vertex_array.reset();
  201. }
  202. DrawParameters RasterizerOpenGL::SetupDraw() {
  203. const auto& gpu = system.GPU().Maxwell3D();
  204. const auto& regs = gpu.regs;
  205. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  206. DrawParameters params{};
  207. params.current_instance = gpu.state.current_instance;
  208. if (regs.draw.topology == Maxwell::PrimitiveTopology::Quads) {
  209. MICROPROFILE_SCOPE(OpenGL_PrimitiveAssembly);
  210. params.use_indexed = true;
  211. params.primitive_mode = GL_TRIANGLES;
  212. if (is_indexed) {
  213. params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
  214. params.count = (regs.index_array.count / 4) * 6;
  215. params.index_buffer_offset = primitive_assembler.MakeQuadIndexed(
  216. regs.index_array.IndexStart(), regs.index_array.FormatSizeInBytes(),
  217. regs.index_array.count);
  218. params.base_vertex = static_cast<GLint>(regs.vb_element_base);
  219. } else {
  220. // MakeQuadArray always generates u32 indexes
  221. params.index_format = GL_UNSIGNED_INT;
  222. params.count = (regs.vertex_buffer.count / 4) * 6;
  223. params.index_buffer_offset =
  224. primitive_assembler.MakeQuadArray(regs.vertex_buffer.first, params.count);
  225. }
  226. return params;
  227. }
  228. params.use_indexed = is_indexed;
  229. params.primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
  230. if (is_indexed) {
  231. MICROPROFILE_SCOPE(OpenGL_Index);
  232. params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
  233. params.count = regs.index_array.count;
  234. params.index_buffer_offset =
  235. buffer_cache.UploadMemory(regs.index_array.IndexStart(), CalculateIndexBufferSize());
  236. params.base_vertex = static_cast<GLint>(regs.vb_element_base);
  237. } else {
  238. params.count = regs.vertex_buffer.count;
  239. params.vertex_first = regs.vertex_buffer.first;
  240. }
  241. return params;
  242. }
  243. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  244. MICROPROFILE_SCOPE(OpenGL_Shader);
  245. auto& gpu = system.GPU().Maxwell3D();
  246. BaseBindings base_bindings;
  247. std::array<bool, Maxwell::NumClipDistances> clip_distances{};
  248. // Prepare packed bindings
  249. bind_ubo_pushbuffer.Setup(base_bindings.cbuf);
  250. bind_ssbo_pushbuffer.Setup(base_bindings.gmem);
  251. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  252. const auto& shader_config = gpu.regs.shader_config[index];
  253. const Maxwell::ShaderProgram program{static_cast<Maxwell::ShaderProgram>(index)};
  254. // Skip stages that are not enabled
  255. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  256. switch (program) {
  257. case Maxwell::ShaderProgram::Geometry:
  258. shader_program_manager->UseTrivialGeometryShader();
  259. break;
  260. }
  261. continue;
  262. }
  263. const std::size_t stage{index == 0 ? 0 : index - 1}; // Stage indices are 0 - 5
  264. GLShader::MaxwellUniformData ubo{};
  265. ubo.SetFromRegs(gpu, stage);
  266. const GLintptr offset = buffer_cache.UploadHostMemory(
  267. &ubo, sizeof(ubo), static_cast<std::size_t>(uniform_buffer_alignment));
  268. // Bind the emulation info buffer
  269. bind_ubo_pushbuffer.Push(buffer_cache.GetHandle(), offset,
  270. static_cast<GLsizeiptr>(sizeof(ubo)));
  271. Shader shader{shader_cache.GetStageProgram(program)};
  272. const auto [program_handle, next_bindings] =
  273. shader->GetProgramHandle(primitive_mode, base_bindings);
  274. switch (program) {
  275. case Maxwell::ShaderProgram::VertexA:
  276. case Maxwell::ShaderProgram::VertexB:
  277. shader_program_manager->UseProgrammableVertexShader(program_handle);
  278. break;
  279. case Maxwell::ShaderProgram::Geometry:
  280. shader_program_manager->UseProgrammableGeometryShader(program_handle);
  281. break;
  282. case Maxwell::ShaderProgram::Fragment:
  283. shader_program_manager->UseProgrammableFragmentShader(program_handle);
  284. break;
  285. default:
  286. UNIMPLEMENTED_MSG("Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  287. shader_config.enable.Value(), shader_config.offset);
  288. }
  289. const auto stage_enum = static_cast<Maxwell::ShaderStage>(stage);
  290. SetupConstBuffers(stage_enum, shader, program_handle, base_bindings);
  291. SetupGlobalRegions(stage_enum, shader, program_handle, base_bindings);
  292. SetupTextures(stage_enum, shader, program_handle, base_bindings);
  293. // Workaround for Intel drivers.
  294. // When a clip distance is enabled but not set in the shader it crops parts of the screen
  295. // (sometimes it's half the screen, sometimes three quarters). To avoid this, enable the
  296. // clip distances only when it's written by a shader stage.
  297. for (std::size_t i = 0; i < Maxwell::NumClipDistances; ++i) {
  298. clip_distances[i] = clip_distances[i] || shader->GetShaderEntries().clip_distances[i];
  299. }
  300. // When VertexA is enabled, we have dual vertex shaders
  301. if (program == Maxwell::ShaderProgram::VertexA) {
  302. // VertexB was combined with VertexA, so we skip the VertexB iteration
  303. index++;
  304. }
  305. base_bindings = next_bindings;
  306. }
  307. bind_ubo_pushbuffer.Bind();
  308. bind_ssbo_pushbuffer.Bind();
  309. SyncClipEnabled(clip_distances);
  310. gpu.dirty_flags.shaders = false;
  311. }
  312. void RasterizerOpenGL::SetupCachedFramebuffer(const FramebufferCacheKey& fbkey,
  313. OpenGLState& current_state) {
  314. const auto [entry, is_cache_miss] = framebuffer_cache.try_emplace(fbkey);
  315. auto& framebuffer = entry->second;
  316. if (is_cache_miss)
  317. framebuffer.Create();
  318. current_state.draw.draw_framebuffer = framebuffer.handle;
  319. current_state.ApplyFramebufferState();
  320. if (!is_cache_miss)
  321. return;
  322. if (fbkey.is_single_buffer) {
  323. if (fbkey.color_attachments[0] != GL_NONE) {
  324. glFramebufferTexture(GL_DRAW_FRAMEBUFFER, fbkey.color_attachments[0], fbkey.colors[0],
  325. 0);
  326. }
  327. glDrawBuffer(fbkey.color_attachments[0]);
  328. } else {
  329. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  330. if (fbkey.colors[index]) {
  331. glFramebufferTexture(GL_DRAW_FRAMEBUFFER,
  332. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index),
  333. fbkey.colors[index], 0);
  334. }
  335. }
  336. glDrawBuffers(fbkey.colors_count, fbkey.color_attachments.data());
  337. }
  338. if (fbkey.zeta) {
  339. GLenum zeta_attachment =
  340. fbkey.stencil_enable ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT;
  341. glFramebufferTexture(GL_DRAW_FRAMEBUFFER, zeta_attachment, fbkey.zeta, 0);
  342. }
  343. }
  344. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  345. const auto& regs = system.GPU().Maxwell3D().regs;
  346. std::size_t size = 0;
  347. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  348. if (!regs.vertex_array[index].IsEnabled())
  349. continue;
  350. const GPUVAddr start = regs.vertex_array[index].StartAddress();
  351. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  352. ASSERT(end > start);
  353. size += end - start + 1;
  354. }
  355. return size;
  356. }
  357. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  358. const auto& regs = system.GPU().Maxwell3D().regs;
  359. return static_cast<std::size_t>(regs.index_array.count) *
  360. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  361. }
  362. bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
  363. accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
  364. DrawArrays();
  365. return true;
  366. }
  367. template <typename Map, typename Interval>
  368. static constexpr auto RangeFromInterval(Map& map, const Interval& interval) {
  369. return boost::make_iterator_range(map.equal_range(interval));
  370. }
  371. void RasterizerOpenGL::UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {
  372. const u64 page_start{addr >> Memory::PAGE_BITS};
  373. const u64 page_end{(addr + size + Memory::PAGE_SIZE - 1) >> Memory::PAGE_BITS};
  374. // Interval maps will erase segments if count reaches 0, so if delta is negative we have to
  375. // subtract after iterating
  376. const auto pages_interval = CachedPageMap::interval_type::right_open(page_start, page_end);
  377. if (delta > 0)
  378. cached_pages.add({pages_interval, delta});
  379. for (const auto& pair : RangeFromInterval(cached_pages, pages_interval)) {
  380. const auto interval = pair.first & pages_interval;
  381. const int count = pair.second;
  382. const VAddr interval_start_addr = boost::icl::first(interval) << Memory::PAGE_BITS;
  383. const VAddr interval_end_addr = boost::icl::last_next(interval) << Memory::PAGE_BITS;
  384. const u64 interval_size = interval_end_addr - interval_start_addr;
  385. if (delta > 0 && count == delta)
  386. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, true);
  387. else if (delta < 0 && count == -delta)
  388. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, false);
  389. else
  390. ASSERT(count >= 0);
  391. }
  392. if (delta < 0)
  393. cached_pages.add({pages_interval, delta});
  394. }
  395. void RasterizerOpenGL::LoadDiskResources(const std::atomic_bool& stop_loading,
  396. const VideoCore::DiskResourceLoadCallback& callback) {
  397. shader_cache.LoadDiskCache(stop_loading, callback);
  398. }
  399. std::pair<bool, bool> RasterizerOpenGL::ConfigureFramebuffers(
  400. OpenGLState& current_state, bool using_color_fb, bool using_depth_fb, bool preserve_contents,
  401. std::optional<std::size_t> single_color_target) {
  402. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  403. auto& gpu = system.GPU().Maxwell3D();
  404. const auto& regs = gpu.regs;
  405. const FramebufferConfigState fb_config_state{using_color_fb, using_depth_fb, preserve_contents,
  406. single_color_target};
  407. if (fb_config_state == current_framebuffer_config_state &&
  408. gpu.dirty_flags.color_buffer.none() && !gpu.dirty_flags.zeta_buffer) {
  409. // Only skip if the previous ConfigureFramebuffers call was from the same kind (multiple or
  410. // single color targets). This is done because the guest registers may not change but the
  411. // host framebuffer may contain different attachments
  412. return current_depth_stencil_usage;
  413. }
  414. current_framebuffer_config_state = fb_config_state;
  415. Surface depth_surface;
  416. if (using_depth_fb) {
  417. depth_surface = res_cache.GetDepthBufferSurface(preserve_contents);
  418. }
  419. UNIMPLEMENTED_IF(regs.rt_separate_frag_data == 0);
  420. // Bind the framebuffer surfaces
  421. current_state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0;
  422. FramebufferCacheKey fbkey;
  423. if (using_color_fb) {
  424. if (single_color_target) {
  425. // Used when just a single color attachment is enabled, e.g. for clearing a color buffer
  426. Surface color_surface =
  427. res_cache.GetColorBufferSurface(*single_color_target, preserve_contents);
  428. if (color_surface) {
  429. // Assume that a surface will be written to if it is used as a framebuffer, even if
  430. // the shader doesn't actually write to it.
  431. color_surface->MarkAsModified(true, res_cache);
  432. // Workaround for and issue in nvidia drivers
  433. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  434. state.framebuffer_srgb.enabled |= color_surface->GetSurfaceParams().srgb_conversion;
  435. }
  436. fbkey.is_single_buffer = true;
  437. fbkey.color_attachments[0] =
  438. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target);
  439. fbkey.colors[0] = color_surface != nullptr ? color_surface->Texture().handle : 0;
  440. } else {
  441. // Multiple color attachments are enabled
  442. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  443. Surface color_surface = res_cache.GetColorBufferSurface(index, preserve_contents);
  444. if (color_surface) {
  445. // Assume that a surface will be written to if it is used as a framebuffer, even
  446. // if the shader doesn't actually write to it.
  447. color_surface->MarkAsModified(true, res_cache);
  448. // Enable sRGB only for supported formats
  449. // Workaround for and issue in nvidia drivers
  450. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  451. state.framebuffer_srgb.enabled |=
  452. color_surface->GetSurfaceParams().srgb_conversion;
  453. }
  454. fbkey.color_attachments[index] =
  455. GL_COLOR_ATTACHMENT0 + regs.rt_control.GetMap(index);
  456. fbkey.colors[index] =
  457. color_surface != nullptr ? color_surface->Texture().handle : 0;
  458. }
  459. fbkey.is_single_buffer = false;
  460. fbkey.colors_count = regs.rt_control.count;
  461. }
  462. } else {
  463. // No color attachments are enabled - leave them as zero
  464. fbkey.is_single_buffer = true;
  465. }
  466. if (depth_surface) {
  467. // Assume that a surface will be written to if it is used as a framebuffer, even if
  468. // the shader doesn't actually write to it.
  469. depth_surface->MarkAsModified(true, res_cache);
  470. fbkey.zeta = depth_surface->Texture().handle;
  471. fbkey.stencil_enable = regs.stencil_enable &&
  472. depth_surface->GetSurfaceParams().type == SurfaceType::DepthStencil;
  473. }
  474. SetupCachedFramebuffer(fbkey, current_state);
  475. SyncViewport(current_state);
  476. return current_depth_stencil_usage = {static_cast<bool>(depth_surface), fbkey.stencil_enable};
  477. }
  478. void RasterizerOpenGL::Clear() {
  479. const auto& regs = system.GPU().Maxwell3D().regs;
  480. bool use_color{};
  481. bool use_depth{};
  482. bool use_stencil{};
  483. OpenGLState clear_state;
  484. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  485. regs.clear_buffers.A) {
  486. use_color = true;
  487. }
  488. if (use_color) {
  489. clear_state.color_mask[0].red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
  490. clear_state.color_mask[0].green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
  491. clear_state.color_mask[0].blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
  492. clear_state.color_mask[0].alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
  493. }
  494. if (regs.clear_buffers.Z) {
  495. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  496. use_depth = true;
  497. // Always enable the depth write when clearing the depth buffer. The depth write mask is
  498. // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to
  499. // true.
  500. clear_state.depth.test_enabled = true;
  501. clear_state.depth.test_func = GL_ALWAYS;
  502. }
  503. if (regs.clear_buffers.S) {
  504. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear stencil but buffer is not enabled!");
  505. use_stencil = true;
  506. clear_state.stencil.test_enabled = true;
  507. if (regs.clear_flags.stencil) {
  508. // Stencil affects the clear so fill it with the used masks
  509. clear_state.stencil.front.test_func = GL_ALWAYS;
  510. clear_state.stencil.front.test_mask = regs.stencil_front_func_mask;
  511. clear_state.stencil.front.action_stencil_fail = GL_KEEP;
  512. clear_state.stencil.front.action_depth_fail = GL_KEEP;
  513. clear_state.stencil.front.action_depth_pass = GL_KEEP;
  514. clear_state.stencil.front.write_mask = regs.stencil_front_mask;
  515. if (regs.stencil_two_side_enable) {
  516. clear_state.stencil.back.test_func = GL_ALWAYS;
  517. clear_state.stencil.back.test_mask = regs.stencil_back_func_mask;
  518. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  519. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  520. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  521. clear_state.stencil.back.write_mask = regs.stencil_back_mask;
  522. } else {
  523. clear_state.stencil.back.test_func = GL_ALWAYS;
  524. clear_state.stencil.back.test_mask = 0xFFFFFFFF;
  525. clear_state.stencil.back.write_mask = 0xFFFFFFFF;
  526. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  527. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  528. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  529. }
  530. }
  531. }
  532. if (!use_color && !use_depth && !use_stencil) {
  533. // No color surface nor depth/stencil surface are enabled
  534. return;
  535. }
  536. const auto [clear_depth, clear_stencil] = ConfigureFramebuffers(
  537. clear_state, use_color, use_depth || use_stencil, false, regs.clear_buffers.RT.Value());
  538. if (regs.clear_flags.scissor) {
  539. SyncScissorTest(clear_state);
  540. }
  541. if (regs.clear_flags.viewport) {
  542. clear_state.EmulateViewportWithScissor();
  543. }
  544. clear_state.ApplyColorMask();
  545. clear_state.ApplyDepth();
  546. clear_state.ApplyStencilTest();
  547. clear_state.ApplyViewport();
  548. if (use_color) {
  549. glClearBufferfv(GL_COLOR, regs.clear_buffers.RT, regs.clear_color);
  550. }
  551. if (clear_depth && clear_stencil) {
  552. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  553. } else if (clear_depth) {
  554. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  555. } else if (clear_stencil) {
  556. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  557. }
  558. }
  559. void RasterizerOpenGL::DrawArrays() {
  560. if (accelerate_draw == AccelDraw::Disabled)
  561. return;
  562. MICROPROFILE_SCOPE(OpenGL_Drawing);
  563. auto& gpu = system.GPU().Maxwell3D();
  564. const auto& regs = gpu.regs;
  565. ConfigureFramebuffers(state);
  566. SyncColorMask();
  567. SyncFragmentColorClampState();
  568. SyncMultiSampleState();
  569. SyncDepthTestState();
  570. SyncStencilTestState();
  571. SyncBlendState();
  572. SyncLogicOpState();
  573. SyncCullMode();
  574. SyncPrimitiveRestart();
  575. SyncScissorTest(state);
  576. // Alpha Testing is synced on shaders.
  577. SyncTransformFeedback();
  578. SyncPointState();
  579. CheckAlphaTests();
  580. SyncPolygonOffset();
  581. // TODO(bunnei): Sync framebuffer_scale uniform here
  582. // TODO(bunnei): Sync scissorbox uniform(s) here
  583. // Draw the vertex batch
  584. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  585. std::size_t buffer_size = CalculateVertexArraysSize();
  586. // Add space for index buffer (keeping in mind non-core primitives)
  587. switch (regs.draw.topology) {
  588. case Maxwell::PrimitiveTopology::Quads:
  589. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) +
  590. primitive_assembler.CalculateQuadSize(regs.vertex_buffer.count);
  591. break;
  592. default:
  593. if (is_indexed) {
  594. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) + CalculateIndexBufferSize();
  595. }
  596. break;
  597. }
  598. // Uniform space for the 5 shader stages
  599. buffer_size =
  600. Common::AlignUp<std::size_t>(buffer_size, 4) +
  601. (sizeof(GLShader::MaxwellUniformData) + uniform_buffer_alignment) * Maxwell::MaxShaderStage;
  602. // Add space for at least 18 constant buffers
  603. buffer_size += Maxwell::MaxConstBuffers * (MaxConstbufferSize + uniform_buffer_alignment);
  604. const bool invalidate = buffer_cache.Map(buffer_size);
  605. if (invalidate) {
  606. // As all cached buffers are invalidated, we need to recheck their state.
  607. gpu.dirty_flags.vertex_array.set();
  608. }
  609. const GLuint vao = SetupVertexFormat();
  610. SetupVertexBuffer(vao);
  611. DrawParameters params = SetupDraw();
  612. SetupShaders(params.primitive_mode);
  613. buffer_cache.Unmap();
  614. shader_program_manager->ApplyTo(state);
  615. state.Apply();
  616. res_cache.SignalPreDrawCall();
  617. params.DispatchDraw();
  618. res_cache.SignalPostDrawCall();
  619. accelerate_draw = AccelDraw::Disabled;
  620. }
  621. void RasterizerOpenGL::FlushAll() {}
  622. void RasterizerOpenGL::FlushRegion(CacheAddr addr, u64 size) {
  623. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  624. if (!addr || !size) {
  625. return;
  626. }
  627. res_cache.FlushRegion(addr, size);
  628. }
  629. void RasterizerOpenGL::InvalidateRegion(CacheAddr addr, u64 size) {
  630. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  631. if (!addr || !size) {
  632. return;
  633. }
  634. res_cache.InvalidateRegion(addr, size);
  635. shader_cache.InvalidateRegion(addr, size);
  636. global_cache.InvalidateRegion(addr, size);
  637. buffer_cache.InvalidateRegion(addr, size);
  638. }
  639. void RasterizerOpenGL::FlushAndInvalidateRegion(CacheAddr addr, u64 size) {
  640. FlushRegion(addr, size);
  641. InvalidateRegion(addr, size);
  642. }
  643. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  644. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  645. const Common::Rectangle<u32>& src_rect,
  646. const Common::Rectangle<u32>& dst_rect) {
  647. MICROPROFILE_SCOPE(OpenGL_Blits);
  648. res_cache.FermiCopySurface(src, dst, src_rect, dst_rect);
  649. return true;
  650. }
  651. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  652. VAddr framebuffer_addr, u32 pixel_stride) {
  653. if (!framebuffer_addr) {
  654. return {};
  655. }
  656. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  657. const auto& surface{res_cache.TryFindFramebufferSurface(Memory::GetPointer(framebuffer_addr))};
  658. if (!surface) {
  659. return {};
  660. }
  661. // Verify that the cached surface is the same size and format as the requested framebuffer
  662. const auto& params{surface->GetSurfaceParams()};
  663. const auto& pixel_format{
  664. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  665. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  666. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  667. if (params.pixel_format != pixel_format) {
  668. LOG_WARNING(Render_OpenGL, "Framebuffer pixel_format is different");
  669. }
  670. screen_info.display_texture = surface->Texture().handle;
  671. return true;
  672. }
  673. void RasterizerOpenGL::SamplerInfo::Create() {
  674. sampler.Create();
  675. mag_filter = Tegra::Texture::TextureFilter::Linear;
  676. min_filter = Tegra::Texture::TextureFilter::Linear;
  677. wrap_u = Tegra::Texture::WrapMode::Wrap;
  678. wrap_v = Tegra::Texture::WrapMode::Wrap;
  679. wrap_p = Tegra::Texture::WrapMode::Wrap;
  680. use_depth_compare = false;
  681. depth_compare_func = Tegra::Texture::DepthCompareFunc::Never;
  682. // OpenGL's default is GL_LINEAR_MIPMAP_LINEAR
  683. glSamplerParameteri(sampler.handle, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  684. glSamplerParameteri(sampler.handle, GL_TEXTURE_COMPARE_FUNC, GL_NEVER);
  685. // Other attributes have correct defaults
  686. }
  687. void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntry& config) {
  688. const GLuint sampler_id = sampler.handle;
  689. if (mag_filter != config.mag_filter) {
  690. mag_filter = config.mag_filter;
  691. glSamplerParameteri(
  692. sampler_id, GL_TEXTURE_MAG_FILTER,
  693. MaxwellToGL::TextureFilterMode(mag_filter, Tegra::Texture::TextureMipmapFilter::None));
  694. }
  695. if (min_filter != config.min_filter || mipmap_filter != config.mipmap_filter) {
  696. min_filter = config.min_filter;
  697. mipmap_filter = config.mipmap_filter;
  698. glSamplerParameteri(sampler_id, GL_TEXTURE_MIN_FILTER,
  699. MaxwellToGL::TextureFilterMode(min_filter, mipmap_filter));
  700. }
  701. if (wrap_u != config.wrap_u) {
  702. wrap_u = config.wrap_u;
  703. glSamplerParameteri(sampler_id, GL_TEXTURE_WRAP_S, MaxwellToGL::WrapMode(wrap_u));
  704. }
  705. if (wrap_v != config.wrap_v) {
  706. wrap_v = config.wrap_v;
  707. glSamplerParameteri(sampler_id, GL_TEXTURE_WRAP_T, MaxwellToGL::WrapMode(wrap_v));
  708. }
  709. if (wrap_p != config.wrap_p) {
  710. wrap_p = config.wrap_p;
  711. glSamplerParameteri(sampler_id, GL_TEXTURE_WRAP_R, MaxwellToGL::WrapMode(wrap_p));
  712. }
  713. if (const bool enabled = config.depth_compare_enabled == 1; use_depth_compare != enabled) {
  714. use_depth_compare = enabled;
  715. glSamplerParameteri(sampler_id, GL_TEXTURE_COMPARE_MODE,
  716. use_depth_compare ? GL_COMPARE_REF_TO_TEXTURE : GL_NONE);
  717. }
  718. if (depth_compare_func != config.depth_compare_func) {
  719. depth_compare_func = config.depth_compare_func;
  720. glSamplerParameteri(sampler_id, GL_TEXTURE_COMPARE_FUNC,
  721. MaxwellToGL::DepthCompareFunc(depth_compare_func));
  722. }
  723. if (const auto new_border_color = config.GetBorderColor(); border_color != new_border_color) {
  724. border_color = new_border_color;
  725. glSamplerParameterfv(sampler_id, GL_TEXTURE_BORDER_COLOR, border_color.data());
  726. }
  727. if (const float anisotropic = config.GetMaxAnisotropy(); max_anisotropic != anisotropic) {
  728. max_anisotropic = anisotropic;
  729. if (GLAD_GL_ARB_texture_filter_anisotropic) {
  730. glSamplerParameterf(sampler_id, GL_TEXTURE_MAX_ANISOTROPY, max_anisotropic);
  731. } else if (GLAD_GL_EXT_texture_filter_anisotropic) {
  732. glSamplerParameterf(sampler_id, GL_TEXTURE_MAX_ANISOTROPY_EXT, max_anisotropic);
  733. }
  734. }
  735. if (const float min = config.GetMinLod(); min_lod != min) {
  736. min_lod = min;
  737. glSamplerParameterf(sampler_id, GL_TEXTURE_MIN_LOD, min_lod);
  738. }
  739. if (const float max = config.GetMaxLod(); max_lod != max) {
  740. max_lod = max;
  741. glSamplerParameterf(sampler_id, GL_TEXTURE_MAX_LOD, max_lod);
  742. }
  743. if (const float bias = config.GetLodBias(); lod_bias != bias) {
  744. lod_bias = bias;
  745. glSamplerParameterf(sampler_id, GL_TEXTURE_LOD_BIAS, lod_bias);
  746. }
  747. }
  748. void RasterizerOpenGL::SetupConstBuffers(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
  749. const Shader& shader, GLuint program_handle,
  750. BaseBindings base_bindings) {
  751. MICROPROFILE_SCOPE(OpenGL_UBO);
  752. const auto& gpu = system.GPU();
  753. const auto& maxwell3d = gpu.Maxwell3D();
  754. const auto& shader_stage = maxwell3d.state.shader_stages[static_cast<std::size_t>(stage)];
  755. const auto& entries = shader->GetShaderEntries().const_buffers;
  756. // Upload only the enabled buffers from the 16 constbuffers of each shader stage
  757. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  758. const auto& used_buffer = entries[bindpoint];
  759. const auto& buffer = shader_stage.const_buffers[used_buffer.GetIndex()];
  760. if (!buffer.enabled) {
  761. // Set values to zero to unbind buffers
  762. bind_ubo_pushbuffer.Push(0, 0, 0);
  763. continue;
  764. }
  765. std::size_t size = 0;
  766. if (used_buffer.IsIndirect()) {
  767. // Buffer is accessed indirectly, so upload the entire thing
  768. size = buffer.size;
  769. if (size > MaxConstbufferSize) {
  770. LOG_WARNING(Render_OpenGL, "Indirect constbuffer size {} exceeds maximum {}", size,
  771. MaxConstbufferSize);
  772. size = MaxConstbufferSize;
  773. }
  774. } else {
  775. // Buffer is accessed directly, upload just what we use
  776. size = used_buffer.GetSize();
  777. }
  778. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  779. // UBO alignment requirements.
  780. size = Common::AlignUp(size, sizeof(GLvec4));
  781. ASSERT_MSG(size <= MaxConstbufferSize, "Constbuffer too big");
  782. const GLintptr const_buffer_offset = buffer_cache.UploadMemory(
  783. buffer.address, size, static_cast<std::size_t>(uniform_buffer_alignment));
  784. bind_ubo_pushbuffer.Push(buffer_cache.GetHandle(), const_buffer_offset, size);
  785. }
  786. }
  787. void RasterizerOpenGL::SetupGlobalRegions(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
  788. const Shader& shader, GLenum primitive_mode,
  789. BaseBindings base_bindings) {
  790. const auto& entries = shader->GetShaderEntries().global_memory_entries;
  791. for (std::size_t bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  792. const auto& entry{entries[bindpoint]};
  793. const auto& region{global_cache.GetGlobalRegion(entry, stage)};
  794. bind_ssbo_pushbuffer.Push(region->GetBufferHandle(), 0,
  795. static_cast<GLsizeiptr>(region->GetSizeInBytes()));
  796. }
  797. }
  798. void RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, const Shader& shader,
  799. GLuint program_handle, BaseBindings base_bindings) {
  800. MICROPROFILE_SCOPE(OpenGL_Texture);
  801. const auto& gpu = system.GPU();
  802. const auto& maxwell3d = gpu.Maxwell3D();
  803. const auto& entries = shader->GetShaderEntries().samplers;
  804. ASSERT_MSG(base_bindings.sampler + entries.size() <= std::size(state.texture_units),
  805. "Exceeded the number of active textures.");
  806. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  807. const auto& entry = entries[bindpoint];
  808. const auto texture = maxwell3d.GetStageTexture(stage, entry.GetOffset());
  809. const u32 current_bindpoint = base_bindings.sampler + bindpoint;
  810. texture_samplers[current_bindpoint].SyncWithConfig(texture.tsc);
  811. if (Surface surface = res_cache.GetTextureSurface(texture, entry); surface) {
  812. state.texture_units[current_bindpoint].texture =
  813. surface->Texture(entry.IsArray()).handle;
  814. surface->UpdateSwizzle(texture.tic.x_source, texture.tic.y_source, texture.tic.z_source,
  815. texture.tic.w_source);
  816. } else {
  817. // Can occur when texture addr is null or its memory is unmapped/invalid
  818. state.texture_units[current_bindpoint].texture = 0;
  819. }
  820. }
  821. }
  822. void RasterizerOpenGL::SyncViewport(OpenGLState& current_state) {
  823. const auto& regs = system.GPU().Maxwell3D().regs;
  824. const bool geometry_shaders_enabled =
  825. regs.IsShaderConfigEnabled(static_cast<size_t>(Maxwell::ShaderProgram::Geometry));
  826. const std::size_t viewport_count =
  827. geometry_shaders_enabled ? Tegra::Engines::Maxwell3D::Regs::NumViewports : 1;
  828. for (std::size_t i = 0; i < viewport_count; i++) {
  829. auto& viewport = current_state.viewports[i];
  830. const auto& src = regs.viewports[i];
  831. const Common::Rectangle<s32> viewport_rect{regs.viewport_transform[i].GetRect()};
  832. viewport.x = viewport_rect.left;
  833. viewport.y = viewport_rect.bottom;
  834. viewport.width = viewport_rect.GetWidth();
  835. viewport.height = viewport_rect.GetHeight();
  836. viewport.depth_range_far = regs.viewports[i].depth_range_far;
  837. viewport.depth_range_near = regs.viewports[i].depth_range_near;
  838. }
  839. state.depth_clamp.far_plane = regs.view_volume_clip_control.depth_clamp_far != 0;
  840. state.depth_clamp.near_plane = regs.view_volume_clip_control.depth_clamp_near != 0;
  841. }
  842. void RasterizerOpenGL::SyncClipEnabled(
  843. const std::array<bool, Maxwell::Regs::NumClipDistances>& clip_mask) {
  844. const auto& regs = system.GPU().Maxwell3D().regs;
  845. const std::array<bool, Maxwell::Regs::NumClipDistances> reg_state{
  846. regs.clip_distance_enabled.c0 != 0, regs.clip_distance_enabled.c1 != 0,
  847. regs.clip_distance_enabled.c2 != 0, regs.clip_distance_enabled.c3 != 0,
  848. regs.clip_distance_enabled.c4 != 0, regs.clip_distance_enabled.c5 != 0,
  849. regs.clip_distance_enabled.c6 != 0, regs.clip_distance_enabled.c7 != 0};
  850. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  851. state.clip_distance[i] = reg_state[i] && clip_mask[i];
  852. }
  853. }
  854. void RasterizerOpenGL::SyncClipCoef() {
  855. UNIMPLEMENTED();
  856. }
  857. void RasterizerOpenGL::SyncCullMode() {
  858. const auto& regs = system.GPU().Maxwell3D().regs;
  859. state.cull.enabled = regs.cull.enabled != 0;
  860. if (state.cull.enabled) {
  861. state.cull.front_face = MaxwellToGL::FrontFace(regs.cull.front_face);
  862. state.cull.mode = MaxwellToGL::CullFace(regs.cull.cull_face);
  863. const bool flip_triangles{regs.screen_y_control.triangle_rast_flip == 0 ||
  864. regs.viewport_transform[0].scale_y < 0.0f};
  865. // If the GPU is configured to flip the rasterized triangles, then we need to flip the
  866. // notion of front and back. Note: We flip the triangles when the value of the register is 0
  867. // because OpenGL already does it for us.
  868. if (flip_triangles) {
  869. if (state.cull.front_face == GL_CCW)
  870. state.cull.front_face = GL_CW;
  871. else if (state.cull.front_face == GL_CW)
  872. state.cull.front_face = GL_CCW;
  873. }
  874. }
  875. }
  876. void RasterizerOpenGL::SyncPrimitiveRestart() {
  877. const auto& regs = system.GPU().Maxwell3D().regs;
  878. state.primitive_restart.enabled = regs.primitive_restart.enabled;
  879. state.primitive_restart.index = regs.primitive_restart.index;
  880. }
  881. void RasterizerOpenGL::SyncDepthTestState() {
  882. const auto& regs = system.GPU().Maxwell3D().regs;
  883. state.depth.test_enabled = regs.depth_test_enable != 0;
  884. state.depth.write_mask = regs.depth_write_enabled ? GL_TRUE : GL_FALSE;
  885. if (!state.depth.test_enabled)
  886. return;
  887. state.depth.test_func = MaxwellToGL::ComparisonOp(regs.depth_test_func);
  888. }
  889. void RasterizerOpenGL::SyncStencilTestState() {
  890. const auto& regs = system.GPU().Maxwell3D().regs;
  891. state.stencil.test_enabled = regs.stencil_enable != 0;
  892. if (!regs.stencil_enable) {
  893. return;
  894. }
  895. state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func);
  896. state.stencil.front.test_ref = regs.stencil_front_func_ref;
  897. state.stencil.front.test_mask = regs.stencil_front_func_mask;
  898. state.stencil.front.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_fail);
  899. state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail);
  900. state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass);
  901. state.stencil.front.write_mask = regs.stencil_front_mask;
  902. if (regs.stencil_two_side_enable) {
  903. state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
  904. state.stencil.back.test_ref = regs.stencil_back_func_ref;
  905. state.stencil.back.test_mask = regs.stencil_back_func_mask;
  906. state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
  907. state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
  908. state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
  909. state.stencil.back.write_mask = regs.stencil_back_mask;
  910. } else {
  911. state.stencil.back.test_func = GL_ALWAYS;
  912. state.stencil.back.test_ref = 0;
  913. state.stencil.back.test_mask = 0xFFFFFFFF;
  914. state.stencil.back.write_mask = 0xFFFFFFFF;
  915. state.stencil.back.action_stencil_fail = GL_KEEP;
  916. state.stencil.back.action_depth_fail = GL_KEEP;
  917. state.stencil.back.action_depth_pass = GL_KEEP;
  918. }
  919. }
  920. void RasterizerOpenGL::SyncColorMask() {
  921. const auto& regs = system.GPU().Maxwell3D().regs;
  922. const std::size_t count =
  923. regs.independent_blend_enable ? Tegra::Engines::Maxwell3D::Regs::NumRenderTargets : 1;
  924. for (std::size_t i = 0; i < count; i++) {
  925. const auto& source = regs.color_mask[regs.color_mask_common ? 0 : i];
  926. auto& dest = state.color_mask[i];
  927. dest.red_enabled = (source.R == 0) ? GL_FALSE : GL_TRUE;
  928. dest.green_enabled = (source.G == 0) ? GL_FALSE : GL_TRUE;
  929. dest.blue_enabled = (source.B == 0) ? GL_FALSE : GL_TRUE;
  930. dest.alpha_enabled = (source.A == 0) ? GL_FALSE : GL_TRUE;
  931. }
  932. }
  933. void RasterizerOpenGL::SyncMultiSampleState() {
  934. const auto& regs = system.GPU().Maxwell3D().regs;
  935. state.multisample_control.alpha_to_coverage = regs.multisample_control.alpha_to_coverage != 0;
  936. state.multisample_control.alpha_to_one = regs.multisample_control.alpha_to_one != 0;
  937. }
  938. void RasterizerOpenGL::SyncFragmentColorClampState() {
  939. const auto& regs = system.GPU().Maxwell3D().regs;
  940. state.fragment_color_clamp.enabled = regs.frag_color_clamp != 0;
  941. }
  942. void RasterizerOpenGL::SyncBlendState() {
  943. const auto& regs = system.GPU().Maxwell3D().regs;
  944. state.blend_color.red = regs.blend_color.r;
  945. state.blend_color.green = regs.blend_color.g;
  946. state.blend_color.blue = regs.blend_color.b;
  947. state.blend_color.alpha = regs.blend_color.a;
  948. state.independant_blend.enabled = regs.independent_blend_enable;
  949. if (!state.independant_blend.enabled) {
  950. auto& blend = state.blend[0];
  951. const auto& src = regs.blend;
  952. blend.enabled = src.enable[0] != 0;
  953. if (blend.enabled) {
  954. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  955. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  956. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  957. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  958. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  959. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  960. }
  961. for (std::size_t i = 1; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  962. state.blend[i].enabled = false;
  963. }
  964. return;
  965. }
  966. for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  967. auto& blend = state.blend[i];
  968. const auto& src = regs.independent_blend[i];
  969. blend.enabled = regs.blend.enable[i] != 0;
  970. if (!blend.enabled)
  971. continue;
  972. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  973. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  974. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  975. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  976. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  977. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  978. }
  979. }
  980. void RasterizerOpenGL::SyncLogicOpState() {
  981. const auto& regs = system.GPU().Maxwell3D().regs;
  982. state.logic_op.enabled = regs.logic_op.enable != 0;
  983. if (!state.logic_op.enabled)
  984. return;
  985. ASSERT_MSG(regs.blend.enable[0] == 0,
  986. "Blending and logic op can't be enabled at the same time.");
  987. state.logic_op.operation = MaxwellToGL::LogicOp(regs.logic_op.operation);
  988. }
  989. void RasterizerOpenGL::SyncScissorTest(OpenGLState& current_state) {
  990. const auto& regs = system.GPU().Maxwell3D().regs;
  991. const bool geometry_shaders_enabled =
  992. regs.IsShaderConfigEnabled(static_cast<size_t>(Maxwell::ShaderProgram::Geometry));
  993. const std::size_t viewport_count =
  994. geometry_shaders_enabled ? Tegra::Engines::Maxwell3D::Regs::NumViewports : 1;
  995. for (std::size_t i = 0; i < viewport_count; i++) {
  996. const auto& src = regs.scissor_test[i];
  997. auto& dst = current_state.viewports[i].scissor;
  998. dst.enabled = (src.enable != 0);
  999. if (dst.enabled == 0) {
  1000. return;
  1001. }
  1002. const u32 width = src.max_x - src.min_x;
  1003. const u32 height = src.max_y - src.min_y;
  1004. dst.x = src.min_x;
  1005. dst.y = src.min_y;
  1006. dst.width = width;
  1007. dst.height = height;
  1008. }
  1009. }
  1010. void RasterizerOpenGL::SyncTransformFeedback() {
  1011. const auto& regs = system.GPU().Maxwell3D().regs;
  1012. UNIMPLEMENTED_IF_MSG(regs.tfb_enabled != 0, "Transform feedbacks are not implemented");
  1013. }
  1014. void RasterizerOpenGL::SyncPointState() {
  1015. const auto& regs = system.GPU().Maxwell3D().regs;
  1016. state.point.size = regs.point_size;
  1017. }
  1018. void RasterizerOpenGL::SyncPolygonOffset() {
  1019. const auto& regs = system.GPU().Maxwell3D().regs;
  1020. state.polygon_offset.fill_enable = regs.polygon_offset_fill_enable != 0;
  1021. state.polygon_offset.line_enable = regs.polygon_offset_line_enable != 0;
  1022. state.polygon_offset.point_enable = regs.polygon_offset_point_enable != 0;
  1023. state.polygon_offset.units = regs.polygon_offset_units;
  1024. state.polygon_offset.factor = regs.polygon_offset_factor;
  1025. state.polygon_offset.clamp = regs.polygon_offset_clamp;
  1026. }
  1027. void RasterizerOpenGL::CheckAlphaTests() {
  1028. const auto& regs = system.GPU().Maxwell3D().regs;
  1029. UNIMPLEMENTED_IF_MSG(regs.alpha_test_enabled != 0 && regs.rt_control.count > 1,
  1030. "Alpha Testing is enabled with more than one rendertarget");
  1031. }
  1032. } // namespace OpenGL