gl_rasterizer.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  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 = SurfaceParams::PixelFormat;
  31. using SurfaceType = SurfaceParams::SurfaceType;
  32. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Array 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. RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo& info)
  42. : emu_window{window}, screen_info{info}, buffer_cache(STREAM_BUFFER_SIZE) {
  43. // Create sampler objects
  44. for (std::size_t i = 0; i < texture_samplers.size(); ++i) {
  45. texture_samplers[i].Create();
  46. state.texture_units[i].sampler = texture_samplers[i].sampler.handle;
  47. }
  48. GLint ext_num;
  49. glGetIntegerv(GL_NUM_EXTENSIONS, &ext_num);
  50. for (GLint i = 0; i < ext_num; i++) {
  51. const std::string_view extension{
  52. reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i))};
  53. if (extension == "GL_ARB_direct_state_access") {
  54. has_ARB_direct_state_access = true;
  55. } else if (extension == "GL_ARB_multi_bind") {
  56. has_ARB_multi_bind = true;
  57. } else if (extension == "GL_ARB_separate_shader_objects") {
  58. has_ARB_separate_shader_objects = true;
  59. } else if (extension == "GL_ARB_vertex_attrib_binding") {
  60. has_ARB_vertex_attrib_binding = true;
  61. }
  62. }
  63. ASSERT_MSG(has_ARB_separate_shader_objects, "has_ARB_separate_shader_objects is unsupported");
  64. // Clipping plane 0 is always enabled for PICA fixed clip plane z <= 0
  65. state.clip_distance[0] = true;
  66. // Create render framebuffer
  67. framebuffer.Create();
  68. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  69. state.draw.shader_program = 0;
  70. state.Apply();
  71. glEnable(GL_BLEND);
  72. glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uniform_buffer_alignment);
  73. LOG_CRITICAL(Render_OpenGL, "Sync fixed function OpenGL state here!");
  74. }
  75. RasterizerOpenGL::~RasterizerOpenGL() {}
  76. void RasterizerOpenGL::SetupVertexArrays() {
  77. MICROPROFILE_SCOPE(OpenGL_VAO);
  78. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  79. const auto& regs = gpu.regs;
  80. auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
  81. auto& VAO = iter->second;
  82. if (is_cache_miss) {
  83. VAO.Create();
  84. state.draw.vertex_array = VAO.handle;
  85. state.Apply();
  86. // The index buffer binding is stored within the VAO. Stupid OpenGL, but easy to work
  87. // around.
  88. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer_cache.GetHandle());
  89. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  90. // Enables the first 16 vertex attributes always, as we don't know which ones are actually
  91. // used until shader time. Note, Tegra technically supports 32, but we're capping this to 16
  92. // for now to avoid OpenGL errors.
  93. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  94. // assume every shader uses them all.
  95. for (unsigned index = 0; index < 16; ++index) {
  96. const auto& attrib = regs.vertex_attrib_format[index];
  97. // Ignore invalid attributes.
  98. if (!attrib.IsValid())
  99. continue;
  100. const auto& buffer = regs.vertex_array[attrib.buffer];
  101. LOG_TRACE(HW_GPU,
  102. "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  103. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  104. attrib.offset.Value(), attrib.IsNormalized());
  105. ASSERT(buffer.IsEnabled());
  106. glEnableVertexAttribArray(index);
  107. if (attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::SignedInt ||
  108. attrib.type ==
  109. Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::UnsignedInt) {
  110. glVertexAttribIFormat(index, attrib.ComponentCount(),
  111. MaxwellToGL::VertexType(attrib), attrib.offset);
  112. } else {
  113. glVertexAttribFormat(index, attrib.ComponentCount(),
  114. MaxwellToGL::VertexType(attrib),
  115. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  116. }
  117. glVertexAttribBinding(index, attrib.buffer);
  118. }
  119. }
  120. state.draw.vertex_array = VAO.handle;
  121. state.draw.vertex_buffer = buffer_cache.GetHandle();
  122. state.Apply();
  123. // Upload all guest vertex arrays sequentially to our buffer
  124. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  125. const auto& vertex_array = regs.vertex_array[index];
  126. if (!vertex_array.IsEnabled())
  127. continue;
  128. Tegra::GPUVAddr start = vertex_array.StartAddress();
  129. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  130. ASSERT(end > start);
  131. const u64 size = end - start + 1;
  132. const GLintptr vertex_buffer_offset = buffer_cache.UploadMemory(start, size);
  133. // Bind the vertex array to the buffer at the current offset.
  134. glBindVertexBuffer(index, buffer_cache.GetHandle(), vertex_buffer_offset,
  135. vertex_array.stride);
  136. if (regs.instanced_arrays.IsInstancingEnabled(index) && vertex_array.divisor != 0) {
  137. // Enable vertex buffer instancing with the specified divisor.
  138. glVertexBindingDivisor(index, vertex_array.divisor);
  139. } else {
  140. // Disable the vertex buffer instancing.
  141. glVertexBindingDivisor(index, 0);
  142. }
  143. }
  144. }
  145. void RasterizerOpenGL::SetupShaders() {
  146. MICROPROFILE_SCOPE(OpenGL_Shader);
  147. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  148. // Next available bindpoints to use when uploading the const buffers and textures to the GLSL
  149. // shaders. The constbuffer bindpoint starts after the shader stage configuration bind points.
  150. u32 current_constbuffer_bindpoint = Tegra::Engines::Maxwell3D::Regs::MaxShaderStage;
  151. u32 current_texture_bindpoint = 0;
  152. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  153. const auto& shader_config = gpu.regs.shader_config[index];
  154. const Maxwell::ShaderProgram program{static_cast<Maxwell::ShaderProgram>(index)};
  155. // Skip stages that are not enabled
  156. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  157. continue;
  158. }
  159. const std::size_t stage{index == 0 ? 0 : index - 1}; // Stage indices are 0 - 5
  160. GLShader::MaxwellUniformData ubo{};
  161. ubo.SetFromRegs(gpu.state.shader_stages[stage]);
  162. const GLintptr offset = buffer_cache.UploadHostMemory(
  163. &ubo, sizeof(ubo), static_cast<std::size_t>(uniform_buffer_alignment));
  164. // Bind the buffer
  165. glBindBufferRange(GL_UNIFORM_BUFFER, stage, buffer_cache.GetHandle(), offset, sizeof(ubo));
  166. Shader shader{shader_cache.GetStageProgram(program)};
  167. switch (program) {
  168. case Maxwell::ShaderProgram::VertexA:
  169. case Maxwell::ShaderProgram::VertexB: {
  170. shader_program_manager->UseProgrammableVertexShader(shader->GetProgramHandle());
  171. break;
  172. }
  173. case Maxwell::ShaderProgram::Fragment: {
  174. shader_program_manager->UseProgrammableFragmentShader(shader->GetProgramHandle());
  175. break;
  176. }
  177. default:
  178. LOG_CRITICAL(HW_GPU, "Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  179. shader_config.enable.Value(), shader_config.offset);
  180. UNREACHABLE();
  181. }
  182. // Configure the const buffers for this shader stage.
  183. current_constbuffer_bindpoint = SetupConstBuffers(static_cast<Maxwell::ShaderStage>(stage),
  184. shader, current_constbuffer_bindpoint);
  185. // Configure the textures for this shader stage.
  186. current_texture_bindpoint = SetupTextures(static_cast<Maxwell::ShaderStage>(stage), shader,
  187. current_texture_bindpoint);
  188. // When VertexA is enabled, we have dual vertex shaders
  189. if (program == Maxwell::ShaderProgram::VertexA) {
  190. // VertexB was combined with VertexA, so we skip the VertexB iteration
  191. index++;
  192. }
  193. }
  194. state.Apply();
  195. shader_program_manager->UseTrivialGeometryShader();
  196. }
  197. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  198. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  199. std::size_t size = 0;
  200. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  201. if (!regs.vertex_array[index].IsEnabled())
  202. continue;
  203. const Tegra::GPUVAddr start = regs.vertex_array[index].StartAddress();
  204. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  205. ASSERT(end > start);
  206. size += end - start + 1;
  207. }
  208. return size;
  209. }
  210. bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
  211. accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
  212. DrawArrays();
  213. return true;
  214. }
  215. template <typename Map, typename Interval>
  216. static constexpr auto RangeFromInterval(Map& map, const Interval& interval) {
  217. return boost::make_iterator_range(map.equal_range(interval));
  218. }
  219. void RasterizerOpenGL::UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {
  220. const u64 page_start{addr >> Memory::PAGE_BITS};
  221. const u64 page_end{(addr + size + Memory::PAGE_SIZE - 1) >> Memory::PAGE_BITS};
  222. // Interval maps will erase segments if count reaches 0, so if delta is negative we have to
  223. // subtract after iterating
  224. const auto pages_interval = CachedPageMap::interval_type::right_open(page_start, page_end);
  225. if (delta > 0)
  226. cached_pages.add({pages_interval, delta});
  227. for (const auto& pair : RangeFromInterval(cached_pages, pages_interval)) {
  228. const auto interval = pair.first & pages_interval;
  229. const int count = pair.second;
  230. const VAddr interval_start_addr = boost::icl::first(interval) << Memory::PAGE_BITS;
  231. const VAddr interval_end_addr = boost::icl::last_next(interval) << Memory::PAGE_BITS;
  232. const u64 interval_size = interval_end_addr - interval_start_addr;
  233. if (delta > 0 && count == delta)
  234. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, true);
  235. else if (delta < 0 && count == -delta)
  236. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, false);
  237. else
  238. ASSERT(count >= 0);
  239. }
  240. if (delta < 0)
  241. cached_pages.add({pages_interval, delta});
  242. }
  243. void RasterizerOpenGL::ConfigureFramebuffers(bool using_color_fb, bool using_depth_fb,
  244. bool preserve_contents,
  245. boost::optional<std::size_t> single_color_target) {
  246. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  247. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  248. Surface depth_surface;
  249. if (using_depth_fb) {
  250. depth_surface = res_cache.GetDepthBufferSurface(preserve_contents);
  251. }
  252. // TODO(bunnei): Figure out how the below register works. According to envytools, this should be
  253. // used to enable multiple render targets. However, it is left unset on all games that I have
  254. // tested.
  255. ASSERT_MSG(regs.rt_separate_frag_data == 0, "Unimplemented");
  256. // Bind the framebuffer surfaces
  257. state.draw.draw_framebuffer = framebuffer.handle;
  258. state.Apply();
  259. if (using_color_fb) {
  260. if (single_color_target) {
  261. // Used when just a single color attachment is enabled, e.g. for clearing a color buffer
  262. Surface color_surface =
  263. res_cache.GetColorBufferSurface(*single_color_target, preserve_contents);
  264. glFramebufferTexture2D(
  265. GL_DRAW_FRAMEBUFFER,
  266. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target), GL_TEXTURE_2D,
  267. color_surface != nullptr ? color_surface->Texture().handle : 0, 0);
  268. glDrawBuffer(GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target));
  269. } else {
  270. // Multiple color attachments are enabled
  271. std::array<GLenum, Maxwell::NumRenderTargets> buffers;
  272. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  273. Surface color_surface = res_cache.GetColorBufferSurface(index, preserve_contents);
  274. buffers[index] = GL_COLOR_ATTACHMENT0 + regs.rt_control.GetMap(index);
  275. glFramebufferTexture2D(
  276. GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index),
  277. GL_TEXTURE_2D, color_surface != nullptr ? color_surface->Texture().handle : 0,
  278. 0);
  279. }
  280. glDrawBuffers(regs.rt_control.count, buffers.data());
  281. }
  282. } else {
  283. // No color attachments are enabled - zero out all of them
  284. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  285. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
  286. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index), GL_TEXTURE_2D,
  287. 0, 0);
  288. }
  289. glDrawBuffer(GL_NONE);
  290. }
  291. if (depth_surface) {
  292. if (regs.stencil_enable) {
  293. // Attach both depth and stencil
  294. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
  295. depth_surface->Texture().handle, 0);
  296. } else {
  297. // Attach depth
  298. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
  299. depth_surface->Texture().handle, 0);
  300. // Clear stencil attachment
  301. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
  302. }
  303. } else {
  304. // Clear both depth and stencil attachment
  305. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0,
  306. 0);
  307. }
  308. SyncViewport();
  309. state.Apply();
  310. }
  311. void RasterizerOpenGL::Clear() {
  312. const auto prev_state{state};
  313. SCOPE_EXIT({ prev_state.Apply(); });
  314. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  315. bool use_color{};
  316. bool use_depth{};
  317. bool use_stencil{};
  318. OpenGLState clear_state;
  319. clear_state.draw.draw_framebuffer = framebuffer.handle;
  320. clear_state.color_mask.red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
  321. clear_state.color_mask.green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
  322. clear_state.color_mask.blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
  323. clear_state.color_mask.alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
  324. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  325. regs.clear_buffers.A) {
  326. use_color = true;
  327. }
  328. if (regs.clear_buffers.Z) {
  329. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  330. use_depth = true;
  331. // Always enable the depth write when clearing the depth buffer. The depth write mask is
  332. // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to true.
  333. clear_state.depth.test_enabled = true;
  334. clear_state.depth.test_func = GL_ALWAYS;
  335. }
  336. if (regs.clear_buffers.S) {
  337. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear stencil but buffer is not enabled!");
  338. use_stencil = true;
  339. clear_state.stencil.test_enabled = true;
  340. }
  341. if (!use_color && !use_depth && !use_stencil) {
  342. // No color surface nor depth/stencil surface are enabled
  343. return;
  344. }
  345. ScopeAcquireGLContext acquire_context{emu_window};
  346. ConfigureFramebuffers(use_color, use_depth || use_stencil, false,
  347. regs.clear_buffers.RT.Value());
  348. clear_state.Apply();
  349. if (use_color) {
  350. glClearBufferfv(GL_COLOR, regs.clear_buffers.RT, regs.clear_color);
  351. }
  352. if (use_depth && use_stencil) {
  353. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  354. } else if (use_depth) {
  355. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  356. } else if (use_stencil) {
  357. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  358. }
  359. }
  360. void RasterizerOpenGL::DrawArrays() {
  361. if (accelerate_draw == AccelDraw::Disabled)
  362. return;
  363. MICROPROFILE_SCOPE(OpenGL_Drawing);
  364. const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
  365. const auto& regs = gpu.regs;
  366. ScopeAcquireGLContext acquire_context{emu_window};
  367. ConfigureFramebuffers();
  368. SyncDepthTestState();
  369. SyncStencilTestState();
  370. SyncBlendState();
  371. SyncLogicOpState();
  372. SyncCullMode();
  373. SyncAlphaTest();
  374. SyncTransformFeedback();
  375. SyncPointState();
  376. // TODO(bunnei): Sync framebuffer_scale uniform here
  377. // TODO(bunnei): Sync scissorbox uniform(s) here
  378. // Draw the vertex batch
  379. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  380. const u64 index_buffer_size{static_cast<u64>(regs.index_array.count) *
  381. static_cast<u64>(regs.index_array.FormatSizeInBytes())};
  382. state.draw.vertex_buffer = buffer_cache.GetHandle();
  383. state.Apply();
  384. std::size_t buffer_size = CalculateVertexArraysSize();
  385. if (is_indexed) {
  386. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) + index_buffer_size;
  387. }
  388. // Uniform space for the 5 shader stages
  389. buffer_size =
  390. Common::AlignUp<std::size_t>(buffer_size, 4) +
  391. (sizeof(GLShader::MaxwellUniformData) + uniform_buffer_alignment) * Maxwell::MaxShaderStage;
  392. // Add space for at least 18 constant buffers
  393. buffer_size += Maxwell::MaxConstBuffers * (MaxConstbufferSize + uniform_buffer_alignment);
  394. buffer_cache.Map(buffer_size);
  395. SetupVertexArrays();
  396. // If indexed mode, copy the index buffer
  397. GLintptr index_buffer_offset = 0;
  398. if (is_indexed) {
  399. MICROPROFILE_SCOPE(OpenGL_Index);
  400. // Adjust the index buffer offset so it points to the first desired index.
  401. auto index_start = regs.index_array.StartAddress();
  402. index_start += static_cast<size_t>(regs.index_array.first) *
  403. static_cast<size_t>(regs.index_array.FormatSizeInBytes());
  404. index_buffer_offset = buffer_cache.UploadMemory(index_start, index_buffer_size);
  405. }
  406. SetupShaders();
  407. buffer_cache.Unmap();
  408. shader_program_manager->ApplyTo(state);
  409. state.Apply();
  410. const GLenum primitive_mode{MaxwellToGL::PrimitiveTopology(regs.draw.topology)};
  411. if (is_indexed) {
  412. const GLint base_vertex{static_cast<GLint>(regs.vb_element_base)};
  413. if (gpu.state.current_instance > 0) {
  414. glDrawElementsInstancedBaseVertexBaseInstance(
  415. primitive_mode, regs.index_array.count,
  416. MaxwellToGL::IndexFormat(regs.index_array.format),
  417. reinterpret_cast<const void*>(index_buffer_offset), 1, base_vertex,
  418. gpu.state.current_instance);
  419. } else {
  420. glDrawElementsBaseVertex(primitive_mode, regs.index_array.count,
  421. MaxwellToGL::IndexFormat(regs.index_array.format),
  422. reinterpret_cast<const void*>(index_buffer_offset),
  423. base_vertex);
  424. }
  425. } else {
  426. if (gpu.state.current_instance > 0) {
  427. glDrawArraysInstancedBaseInstance(primitive_mode, regs.vertex_buffer.first,
  428. regs.vertex_buffer.count, 1,
  429. gpu.state.current_instance);
  430. } else {
  431. glDrawArrays(primitive_mode, regs.vertex_buffer.first, regs.vertex_buffer.count);
  432. }
  433. }
  434. // Disable scissor test
  435. state.scissor.enabled = false;
  436. accelerate_draw = AccelDraw::Disabled;
  437. // Unbind textures for potential future use as framebuffer attachments
  438. for (auto& texture_unit : state.texture_units) {
  439. texture_unit.Unbind();
  440. }
  441. state.Apply();
  442. }
  443. void RasterizerOpenGL::FlushAll() {}
  444. void RasterizerOpenGL::FlushRegion(VAddr addr, u64 size) {}
  445. void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size) {
  446. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  447. res_cache.InvalidateRegion(addr, size);
  448. shader_cache.InvalidateRegion(addr, size);
  449. buffer_cache.InvalidateRegion(addr, size);
  450. }
  451. void RasterizerOpenGL::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  452. InvalidateRegion(addr, size);
  453. }
  454. bool RasterizerOpenGL::AccelerateDisplayTransfer(const void* config) {
  455. MICROPROFILE_SCOPE(OpenGL_Blits);
  456. UNREACHABLE();
  457. return true;
  458. }
  459. bool RasterizerOpenGL::AccelerateTextureCopy(const void* config) {
  460. UNREACHABLE();
  461. return true;
  462. }
  463. bool RasterizerOpenGL::AccelerateFill(const void* config) {
  464. UNREACHABLE();
  465. return true;
  466. }
  467. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  468. VAddr framebuffer_addr, u32 pixel_stride) {
  469. if (!framebuffer_addr) {
  470. return {};
  471. }
  472. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  473. const auto& surface{res_cache.TryFindFramebufferSurface(framebuffer_addr)};
  474. if (!surface) {
  475. return {};
  476. }
  477. // Verify that the cached surface is the same size and format as the requested framebuffer
  478. const auto& params{surface->GetSurfaceParams()};
  479. const auto& pixel_format{SurfaceParams::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  480. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  481. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  482. ASSERT_MSG(params.pixel_format == pixel_format, "Framebuffer pixel_format is different");
  483. screen_info.display_texture = surface->Texture().handle;
  484. return true;
  485. }
  486. void RasterizerOpenGL::SamplerInfo::Create() {
  487. sampler.Create();
  488. mag_filter = min_filter = Tegra::Texture::TextureFilter::Linear;
  489. wrap_u = wrap_v = wrap_p = Tegra::Texture::WrapMode::Wrap;
  490. // default is GL_LINEAR_MIPMAP_LINEAR
  491. glSamplerParameteri(sampler.handle, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  492. // Other attributes have correct defaults
  493. }
  494. void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntry& config) {
  495. const GLuint s = sampler.handle;
  496. if (mag_filter != config.mag_filter) {
  497. mag_filter = config.mag_filter;
  498. glSamplerParameteri(s, GL_TEXTURE_MAG_FILTER, MaxwellToGL::TextureFilterMode(mag_filter));
  499. }
  500. if (min_filter != config.min_filter) {
  501. min_filter = config.min_filter;
  502. glSamplerParameteri(s, GL_TEXTURE_MIN_FILTER, MaxwellToGL::TextureFilterMode(min_filter));
  503. }
  504. if (wrap_u != config.wrap_u) {
  505. wrap_u = config.wrap_u;
  506. glSamplerParameteri(s, GL_TEXTURE_WRAP_S, MaxwellToGL::WrapMode(wrap_u));
  507. }
  508. if (wrap_v != config.wrap_v) {
  509. wrap_v = config.wrap_v;
  510. glSamplerParameteri(s, GL_TEXTURE_WRAP_T, MaxwellToGL::WrapMode(wrap_v));
  511. }
  512. if (wrap_p != config.wrap_p) {
  513. wrap_p = config.wrap_p;
  514. glSamplerParameteri(s, GL_TEXTURE_WRAP_R, MaxwellToGL::WrapMode(wrap_p));
  515. }
  516. if (wrap_u == Tegra::Texture::WrapMode::Border || wrap_v == Tegra::Texture::WrapMode::Border ||
  517. wrap_p == Tegra::Texture::WrapMode::Border) {
  518. const GLvec4 new_border_color = {{config.border_color_r, config.border_color_g,
  519. config.border_color_b, config.border_color_a}};
  520. if (border_color != new_border_color) {
  521. border_color = new_border_color;
  522. glSamplerParameterfv(s, GL_TEXTURE_BORDER_COLOR, border_color.data());
  523. }
  524. }
  525. }
  526. u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shader,
  527. u32 current_bindpoint) {
  528. MICROPROFILE_SCOPE(OpenGL_UBO);
  529. const auto& gpu = Core::System::GetInstance().GPU();
  530. const auto& maxwell3d = gpu.Maxwell3D();
  531. const auto& shader_stage = maxwell3d.state.shader_stages[static_cast<std::size_t>(stage)];
  532. const auto& entries = shader->GetShaderEntries().const_buffer_entries;
  533. constexpr u64 max_binds = Tegra::Engines::Maxwell3D::Regs::MaxConstBuffers;
  534. std::array<GLuint, max_binds> bind_buffers;
  535. std::array<GLintptr, max_binds> bind_offsets;
  536. std::array<GLsizeiptr, max_binds> bind_sizes;
  537. ASSERT_MSG(entries.size() <= max_binds, "Exceeded expected number of binding points.");
  538. // Upload only the enabled buffers from the 16 constbuffers of each shader stage
  539. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  540. const auto& used_buffer = entries[bindpoint];
  541. const auto& buffer = shader_stage.const_buffers[used_buffer.GetIndex()];
  542. if (!buffer.enabled) {
  543. // With disabled buffers set values as zero to unbind them
  544. bind_buffers[bindpoint] = 0;
  545. bind_offsets[bindpoint] = 0;
  546. bind_sizes[bindpoint] = 0;
  547. continue;
  548. }
  549. std::size_t size = 0;
  550. if (used_buffer.IsIndirect()) {
  551. // Buffer is accessed indirectly, so upload the entire thing
  552. size = buffer.size;
  553. if (size > MaxConstbufferSize) {
  554. LOG_CRITICAL(HW_GPU, "indirect constbuffer size {} exceeds maximum {}", size,
  555. MaxConstbufferSize);
  556. size = MaxConstbufferSize;
  557. }
  558. } else {
  559. // Buffer is accessed directly, upload just what we use
  560. size = used_buffer.GetSize() * sizeof(float);
  561. }
  562. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  563. // UBO alignment requirements.
  564. size = Common::AlignUp(size, sizeof(GLvec4));
  565. ASSERT_MSG(size <= MaxConstbufferSize, "Constbuffer too big");
  566. GLintptr const_buffer_offset = buffer_cache.UploadMemory(
  567. buffer.address, size, static_cast<std::size_t>(uniform_buffer_alignment));
  568. // Now configure the bindpoint of the buffer inside the shader
  569. glUniformBlockBinding(shader->GetProgramHandle(),
  570. shader->GetProgramResourceIndex(used_buffer),
  571. current_bindpoint + bindpoint);
  572. // Prepare values for multibind
  573. bind_buffers[bindpoint] = buffer_cache.GetHandle();
  574. bind_offsets[bindpoint] = const_buffer_offset;
  575. bind_sizes[bindpoint] = size;
  576. }
  577. glBindBuffersRange(GL_UNIFORM_BUFFER, current_bindpoint, static_cast<GLsizei>(entries.size()),
  578. bind_buffers.data(), bind_offsets.data(), bind_sizes.data());
  579. return current_bindpoint + static_cast<u32>(entries.size());
  580. }
  581. u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, Shader& shader, u32 current_unit) {
  582. MICROPROFILE_SCOPE(OpenGL_Texture);
  583. const auto& gpu = Core::System::GetInstance().GPU();
  584. const auto& maxwell3d = gpu.Maxwell3D();
  585. const auto& entries = shader->GetShaderEntries().texture_samplers;
  586. ASSERT_MSG(current_unit + entries.size() <= std::size(state.texture_units),
  587. "Exceeded the number of active textures.");
  588. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  589. const auto& entry = entries[bindpoint];
  590. const u32 current_bindpoint = current_unit + bindpoint;
  591. // Bind the uniform to the sampler.
  592. glProgramUniform1i(shader->GetProgramHandle(), shader->GetUniformLocation(entry),
  593. current_bindpoint);
  594. const auto texture = maxwell3d.GetStageTexture(entry.GetStage(), entry.GetOffset());
  595. if (!texture.enabled) {
  596. state.texture_units[current_bindpoint].texture = 0;
  597. continue;
  598. }
  599. texture_samplers[current_bindpoint].SyncWithConfig(texture.tsc);
  600. Surface surface = res_cache.GetTextureSurface(texture, entry);
  601. if (surface != nullptr) {
  602. state.texture_units[current_bindpoint].texture = surface->Texture().handle;
  603. state.texture_units[current_bindpoint].target = surface->Target();
  604. state.texture_units[current_bindpoint].swizzle.r =
  605. MaxwellToGL::SwizzleSource(texture.tic.x_source);
  606. state.texture_units[current_bindpoint].swizzle.g =
  607. MaxwellToGL::SwizzleSource(texture.tic.y_source);
  608. state.texture_units[current_bindpoint].swizzle.b =
  609. MaxwellToGL::SwizzleSource(texture.tic.z_source);
  610. state.texture_units[current_bindpoint].swizzle.a =
  611. MaxwellToGL::SwizzleSource(texture.tic.w_source);
  612. } else {
  613. // Can occur when texture addr is null or its memory is unmapped/invalid
  614. state.texture_units[current_bindpoint].texture = 0;
  615. }
  616. }
  617. return current_unit + static_cast<u32>(entries.size());
  618. }
  619. void RasterizerOpenGL::SyncViewport() {
  620. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  621. const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[0].GetRect()};
  622. state.viewport.x = viewport_rect.left;
  623. state.viewport.y = viewport_rect.bottom;
  624. state.viewport.width = static_cast<GLsizei>(viewport_rect.GetWidth());
  625. state.viewport.height = static_cast<GLsizei>(viewport_rect.GetHeight());
  626. }
  627. void RasterizerOpenGL::SyncClipEnabled() {
  628. UNREACHABLE();
  629. }
  630. void RasterizerOpenGL::SyncClipCoef() {
  631. UNREACHABLE();
  632. }
  633. void RasterizerOpenGL::SyncCullMode() {
  634. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  635. state.cull.enabled = regs.cull.enabled != 0;
  636. if (state.cull.enabled) {
  637. state.cull.front_face = MaxwellToGL::FrontFace(regs.cull.front_face);
  638. state.cull.mode = MaxwellToGL::CullFace(regs.cull.cull_face);
  639. const bool flip_triangles{regs.screen_y_control.triangle_rast_flip == 0 ||
  640. regs.viewport_transform[0].scale_y < 0.0f};
  641. // If the GPU is configured to flip the rasterized triangles, then we need to flip the
  642. // notion of front and back. Note: We flip the triangles when the value of the register is 0
  643. // because OpenGL already does it for us.
  644. if (flip_triangles) {
  645. if (state.cull.front_face == GL_CCW)
  646. state.cull.front_face = GL_CW;
  647. else if (state.cull.front_face == GL_CW)
  648. state.cull.front_face = GL_CCW;
  649. }
  650. }
  651. }
  652. void RasterizerOpenGL::SyncDepthScale() {
  653. UNREACHABLE();
  654. }
  655. void RasterizerOpenGL::SyncDepthOffset() {
  656. UNREACHABLE();
  657. }
  658. void RasterizerOpenGL::SyncDepthTestState() {
  659. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  660. state.depth.test_enabled = regs.depth_test_enable != 0;
  661. state.depth.write_mask = regs.depth_write_enabled ? GL_TRUE : GL_FALSE;
  662. if (!state.depth.test_enabled)
  663. return;
  664. state.depth.test_func = MaxwellToGL::ComparisonOp(regs.depth_test_func);
  665. }
  666. void RasterizerOpenGL::SyncStencilTestState() {
  667. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  668. state.stencil.test_enabled = regs.stencil_enable != 0;
  669. if (!regs.stencil_enable) {
  670. return;
  671. }
  672. // TODO(bunnei): Verify behavior when this is not set
  673. ASSERT(regs.stencil_two_side_enable);
  674. state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func);
  675. state.stencil.front.test_ref = regs.stencil_front_func_ref;
  676. state.stencil.front.test_mask = regs.stencil_front_func_mask;
  677. state.stencil.front.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_fail);
  678. state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail);
  679. state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass);
  680. state.stencil.front.write_mask = regs.stencil_front_mask;
  681. state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
  682. state.stencil.back.test_ref = regs.stencil_back_func_ref;
  683. state.stencil.back.test_mask = regs.stencil_back_func_mask;
  684. state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
  685. state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
  686. state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
  687. state.stencil.back.write_mask = regs.stencil_back_mask;
  688. }
  689. void RasterizerOpenGL::SyncBlendState() {
  690. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  691. // TODO(Subv): Support more than just render target 0.
  692. state.blend.enabled = regs.blend.enable[0] != 0;
  693. if (!state.blend.enabled)
  694. return;
  695. ASSERT_MSG(regs.logic_op.enable == 0,
  696. "Blending and logic op can't be enabled at the same time.");
  697. ASSERT_MSG(regs.independent_blend_enable == 1, "Only independent blending is implemented");
  698. ASSERT_MSG(!regs.independent_blend[0].separate_alpha, "Unimplemented");
  699. state.blend.rgb_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_rgb);
  700. state.blend.src_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_rgb);
  701. state.blend.dst_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_rgb);
  702. state.blend.a_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_a);
  703. state.blend.src_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_a);
  704. state.blend.dst_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_a);
  705. }
  706. void RasterizerOpenGL::SyncLogicOpState() {
  707. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  708. // TODO(Subv): Support more than just render target 0.
  709. state.logic_op.enabled = regs.logic_op.enable != 0;
  710. if (!state.logic_op.enabled)
  711. return;
  712. ASSERT_MSG(regs.blend.enable[0] == 0,
  713. "Blending and logic op can't be enabled at the same time.");
  714. state.logic_op.operation = MaxwellToGL::LogicOp(regs.logic_op.operation);
  715. }
  716. void RasterizerOpenGL::SyncAlphaTest() {
  717. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  718. // TODO(Rodrigo): Alpha testing is a legacy OpenGL feature, but it can be
  719. // implemented with a test+discard in fragment shaders.
  720. if (regs.alpha_test_enabled != 0) {
  721. LOG_CRITICAL(Render_OpenGL, "Alpha testing is not implemented");
  722. UNREACHABLE();
  723. }
  724. }
  725. void RasterizerOpenGL::SyncTransformFeedback() {
  726. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  727. if (regs.tfb_enabled != 0) {
  728. LOG_CRITICAL(Render_OpenGL, "Transform feedbacks are not implemented");
  729. UNREACHABLE();
  730. }
  731. }
  732. void RasterizerOpenGL::SyncPointState() {
  733. const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
  734. state.point.size = regs.point_size;
  735. }
  736. } // namespace OpenGL