gl_rasterizer.cpp 34 KB

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