gl_rasterizer.cpp 38 KB

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