gl_rasterizer.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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 <tuple>
  8. #include <utility>
  9. #include <glad/glad.h>
  10. #include "common/alignment.h"
  11. #include "common/assert.h"
  12. #include "common/logging/log.h"
  13. #include "common/math_util.h"
  14. #include "common/microprofile.h"
  15. #include "common/scope_exit.h"
  16. #include "core/core.h"
  17. #include "core/hle/kernel/process.h"
  18. #include "core/settings.h"
  19. #include "video_core/engines/maxwell_3d.h"
  20. #include "video_core/renderer_opengl/gl_rasterizer.h"
  21. #include "video_core/renderer_opengl/gl_shader_gen.h"
  22. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  23. #include "video_core/renderer_opengl/renderer_opengl.h"
  24. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  25. using PixelFormat = SurfaceParams::PixelFormat;
  26. using SurfaceType = SurfaceParams::SurfaceType;
  27. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Array Setup", MP_RGB(128, 128, 192));
  28. MICROPROFILE_DEFINE(OpenGL_VS, "OpenGL", "Vertex Shader Setup", MP_RGB(128, 128, 192));
  29. MICROPROFILE_DEFINE(OpenGL_FS, "OpenGL", "Fragment Shader Setup", MP_RGB(128, 128, 192));
  30. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  31. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(100, 100, 255));
  32. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
  33. RasterizerOpenGL::RasterizerOpenGL() {
  34. has_ARB_buffer_storage = false;
  35. has_ARB_direct_state_access = false;
  36. has_ARB_separate_shader_objects = false;
  37. has_ARB_vertex_attrib_binding = false;
  38. // Create sampler objects
  39. for (size_t i = 0; i < texture_samplers.size(); ++i) {
  40. texture_samplers[i].Create();
  41. state.texture_units[i].sampler = texture_samplers[i].sampler.handle;
  42. }
  43. // Create SSBOs
  44. for (size_t stage = 0; stage < ssbos.size(); ++stage) {
  45. for (size_t buffer = 0; buffer < ssbos[stage].size(); ++buffer) {
  46. ssbos[stage][buffer].Create();
  47. state.draw.const_buffers[stage][buffer].ssbo = ssbos[stage][buffer].handle;
  48. }
  49. }
  50. GLint ext_num;
  51. glGetIntegerv(GL_NUM_EXTENSIONS, &ext_num);
  52. for (GLint i = 0; i < ext_num; i++) {
  53. std::string extension{reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i))};
  54. if (extension == "GL_ARB_buffer_storage") {
  55. has_ARB_buffer_storage = true;
  56. } else if (extension == "GL_ARB_direct_state_access") {
  57. has_ARB_direct_state_access = true;
  58. } else if (extension == "GL_ARB_separate_shader_objects") {
  59. has_ARB_separate_shader_objects = true;
  60. } else if (extension == "GL_ARB_vertex_attrib_binding") {
  61. has_ARB_vertex_attrib_binding = true;
  62. }
  63. }
  64. ASSERT_MSG(has_ARB_separate_shader_objects, "has_ARB_separate_shader_objects is unsupported");
  65. // Clipping plane 0 is always enabled for PICA fixed clip plane z <= 0
  66. state.clip_distance[0] = true;
  67. // Generate VAO and UBO
  68. sw_vao.Create();
  69. uniform_buffer.Create();
  70. state.draw.vertex_array = sw_vao.handle;
  71. state.draw.uniform_buffer = uniform_buffer.handle;
  72. state.Apply();
  73. // Create render framebuffer
  74. framebuffer.Create();
  75. hw_vao.Create();
  76. stream_buffer = OGLStreamBuffer::MakeBuffer(has_ARB_buffer_storage, GL_ARRAY_BUFFER);
  77. stream_buffer->Create(STREAM_BUFFER_SIZE, STREAM_BUFFER_SIZE / 2);
  78. state.draw.vertex_buffer = stream_buffer->GetHandle();
  79. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  80. state.draw.shader_program = 0;
  81. state.draw.vertex_array = hw_vao.handle;
  82. state.Apply();
  83. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, stream_buffer->GetHandle());
  84. for (unsigned index = 0; index < uniform_buffers.size(); ++index) {
  85. auto& buffer = uniform_buffers[index];
  86. buffer.Create();
  87. glBindBuffer(GL_UNIFORM_BUFFER, buffer.handle);
  88. glBufferData(GL_UNIFORM_BUFFER, sizeof(GLShader::MaxwellUniformData), nullptr,
  89. GL_STREAM_COPY);
  90. glBindBufferBase(GL_UNIFORM_BUFFER, index, buffer.handle);
  91. }
  92. accelerate_draw = AccelDraw::Disabled;
  93. glEnable(GL_BLEND);
  94. NGLOG_CRITICAL(Render_OpenGL, "Sync fixed function OpenGL state here!");
  95. }
  96. RasterizerOpenGL::~RasterizerOpenGL() {
  97. if (stream_buffer != nullptr) {
  98. state.draw.vertex_buffer = stream_buffer->GetHandle();
  99. state.Apply();
  100. stream_buffer->Release();
  101. }
  102. }
  103. std::pair<u8*, GLintptr> RasterizerOpenGL::SetupVertexArrays(u8* array_ptr,
  104. GLintptr buffer_offset) {
  105. MICROPROFILE_SCOPE(OpenGL_VAO);
  106. const auto& regs = Core::System().GetInstance().GPU().Maxwell3D().regs;
  107. const auto& memory_manager = Core::System().GetInstance().GPU().memory_manager;
  108. state.draw.vertex_array = hw_vao.handle;
  109. state.draw.vertex_buffer = stream_buffer->GetHandle();
  110. state.Apply();
  111. // Upload all guest vertex arrays sequentially to our buffer
  112. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  113. const auto& vertex_array = regs.vertex_array[index];
  114. if (!vertex_array.IsEnabled())
  115. continue;
  116. const Tegra::GPUVAddr start = vertex_array.StartAddress();
  117. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  118. ASSERT(end > start);
  119. u64 size = end - start + 1;
  120. // Copy vertex array data
  121. Memory::ReadBlock(*memory_manager->GpuToCpuAddress(start), array_ptr, size);
  122. // Bind the vertex array to the buffer at the current offset.
  123. glBindVertexBuffer(index, stream_buffer->GetHandle(), buffer_offset, vertex_array.stride);
  124. ASSERT_MSG(vertex_array.divisor == 0, "Vertex buffer divisor unimplemented");
  125. array_ptr += size;
  126. buffer_offset += size;
  127. }
  128. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  129. // Enables the first 16 vertex attributes always, as we don't know which ones are actually used
  130. // until shader time. Note, Tegra technically supports 32, but we're capping this to 16 for now
  131. // to avoid OpenGL errors.
  132. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  133. // assume every shader uses them all.
  134. for (unsigned index = 0; index < 16; ++index) {
  135. auto& attrib = regs.vertex_attrib_format[index];
  136. NGLOG_DEBUG(HW_GPU, "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  137. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  138. attrib.offset.Value(), attrib.IsNormalized());
  139. auto& buffer = regs.vertex_array[attrib.buffer];
  140. ASSERT(buffer.IsEnabled());
  141. glEnableVertexAttribArray(index);
  142. glVertexAttribFormat(index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  143. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  144. glVertexAttribBinding(index, attrib.buffer);
  145. }
  146. return {array_ptr, buffer_offset};
  147. }
  148. void RasterizerOpenGL::SetupShaders(u8* buffer_ptr, GLintptr buffer_offset) {
  149. // Helper function for uploading uniform data
  150. const auto copy_buffer = [&](GLuint handle, GLintptr offset, GLsizeiptr size) {
  151. if (has_ARB_direct_state_access) {
  152. glCopyNamedBufferSubData(stream_buffer->GetHandle(), handle, offset, 0, size);
  153. } else {
  154. glBindBuffer(GL_COPY_WRITE_BUFFER, handle);
  155. glCopyBufferSubData(GL_ARRAY_BUFFER, GL_COPY_WRITE_BUFFER, offset, 0, size);
  156. }
  157. };
  158. auto& gpu = Core::System().GetInstance().GPU().Maxwell3D();
  159. ASSERT_MSG(!gpu.regs.shader_config[0].enable, "VertexA is unsupported!");
  160. // Next available bindpoints to use when uploading the const buffers and textures to the GLSL
  161. // shaders. The constbuffer bindpoint starts after the shader stage configuration bind points.
  162. u32 current_constbuffer_bindpoint = uniform_buffers.size();
  163. u32 current_texture_bindpoint = 0;
  164. for (unsigned index = 1; index < Maxwell::MaxShaderProgram; ++index) {
  165. auto& shader_config = gpu.regs.shader_config[index];
  166. const Maxwell::ShaderProgram program{static_cast<Maxwell::ShaderProgram>(index)};
  167. const auto& stage = index - 1; // Stage indices are 0 - 5
  168. const bool is_enabled = gpu.IsShaderStageEnabled(static_cast<Maxwell::ShaderStage>(stage));
  169. // Skip stages that are not enabled
  170. if (!is_enabled) {
  171. continue;
  172. }
  173. GLShader::MaxwellUniformData ubo{};
  174. ubo.SetFromRegs(gpu.state.shader_stages[stage]);
  175. std::memcpy(buffer_ptr, &ubo, sizeof(ubo));
  176. // Flush the buffer so that the GPU can see the data we just wrote.
  177. glFlushMappedBufferRange(GL_ARRAY_BUFFER, buffer_offset, sizeof(ubo));
  178. // Upload uniform data as one UBO per stage
  179. const GLintptr ubo_offset = buffer_offset;
  180. copy_buffer(uniform_buffers[stage].handle, ubo_offset,
  181. sizeof(GLShader::MaxwellUniformData));
  182. buffer_ptr += sizeof(GLShader::MaxwellUniformData);
  183. buffer_offset += sizeof(GLShader::MaxwellUniformData);
  184. // Fetch program code from memory
  185. GLShader::ProgramCode program_code;
  186. const u64 gpu_address{gpu.regs.code_address.CodeAddress() + shader_config.offset};
  187. const boost::optional<VAddr> cpu_address{gpu.memory_manager.GpuToCpuAddress(gpu_address)};
  188. Memory::ReadBlock(*cpu_address, program_code.data(), program_code.size() * sizeof(u64));
  189. GLShader::ShaderSetup setup{std::move(program_code)};
  190. GLShader::ShaderEntries shader_resources;
  191. switch (program) {
  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. NGLOG_CRITICAL(HW_GPU, "Unimplemented shader index={}, enable={}, offset=0x{:08X}",
  206. index, 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. current_constbuffer_bindpoint =
  213. SetupConstBuffers(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. }
  220. shader_program_manager->UseTrivialGeometryShader();
  221. }
  222. size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  223. const auto& regs = Core::System().GetInstance().GPU().Maxwell3D().regs;
  224. size_t size = 0;
  225. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  226. if (!regs.vertex_array[index].IsEnabled())
  227. continue;
  228. const Tegra::GPUVAddr start = regs.vertex_array[index].StartAddress();
  229. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  230. ASSERT(end > start);
  231. size += end - start + 1;
  232. }
  233. return size;
  234. }
  235. bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
  236. accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
  237. DrawArrays();
  238. return true;
  239. }
  240. void RasterizerOpenGL::DrawArrays() {
  241. if (accelerate_draw == AccelDraw::Disabled)
  242. return;
  243. MICROPROFILE_SCOPE(OpenGL_Drawing);
  244. const auto& regs = Core::System().GetInstance().GPU().Maxwell3D().regs;
  245. // TODO(bunnei): Implement these
  246. const bool has_stencil = false;
  247. const bool using_color_fb = true;
  248. const bool using_depth_fb = false;
  249. const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[0].GetRect()};
  250. const bool write_color_fb =
  251. state.color_mask.red_enabled == GL_TRUE || state.color_mask.green_enabled == GL_TRUE ||
  252. state.color_mask.blue_enabled == GL_TRUE || state.color_mask.alpha_enabled == GL_TRUE;
  253. const bool write_depth_fb =
  254. (state.depth.test_enabled && state.depth.write_mask == GL_TRUE) ||
  255. (has_stencil && state.stencil.test_enabled && state.stencil.write_mask != 0);
  256. Surface color_surface;
  257. Surface depth_surface;
  258. MathUtil::Rectangle<u32> surfaces_rect;
  259. std::tie(color_surface, depth_surface, surfaces_rect) =
  260. res_cache.GetFramebufferSurfaces(using_color_fb, using_depth_fb, viewport_rect);
  261. MathUtil::Rectangle<u32> draw_rect{
  262. static_cast<u32>(std::clamp<s32>(static_cast<s32>(surfaces_rect.left) + viewport_rect.left,
  263. surfaces_rect.left, surfaces_rect.right)), // Left
  264. static_cast<u32>(std::clamp<s32>(static_cast<s32>(surfaces_rect.bottom) + viewport_rect.top,
  265. surfaces_rect.bottom, surfaces_rect.top)), // Top
  266. static_cast<u32>(std::clamp<s32>(static_cast<s32>(surfaces_rect.left) + viewport_rect.right,
  267. surfaces_rect.left, surfaces_rect.right)), // Right
  268. static_cast<u32>(
  269. std::clamp<s32>(static_cast<s32>(surfaces_rect.bottom) + viewport_rect.bottom,
  270. surfaces_rect.bottom, surfaces_rect.top))}; // Bottom
  271. // Bind the framebuffer surfaces
  272. BindFramebufferSurfaces(color_surface, depth_surface, has_stencil);
  273. // Sync the viewport
  274. SyncViewport(surfaces_rect);
  275. // Sync the blend state registers
  276. SyncBlendState();
  277. // TODO(bunnei): Sync framebuffer_scale uniform here
  278. // TODO(bunnei): Sync scissorbox uniform(s) here
  279. // Viewport can have negative offsets or larger dimensions than our framebuffer sub-rect. Enable
  280. // scissor test to prevent drawing outside of the framebuffer region
  281. state.scissor.enabled = true;
  282. state.scissor.x = draw_rect.left;
  283. state.scissor.y = draw_rect.bottom;
  284. state.scissor.width = draw_rect.GetWidth();
  285. state.scissor.height = draw_rect.GetHeight();
  286. state.Apply();
  287. // Draw the vertex batch
  288. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  289. const u64 index_buffer_size{regs.index_array.count * regs.index_array.FormatSizeInBytes()};
  290. const unsigned vertex_num{is_indexed ? regs.index_array.count : regs.vertex_buffer.count};
  291. state.draw.vertex_buffer = stream_buffer->GetHandle();
  292. state.Apply();
  293. size_t buffer_size = CalculateVertexArraysSize();
  294. if (is_indexed) {
  295. buffer_size = Common::AlignUp<size_t>(buffer_size, 4) + index_buffer_size;
  296. }
  297. // Uniform space for the 5 shader stages
  298. buffer_size = Common::AlignUp<size_t>(buffer_size, 4) +
  299. sizeof(GLShader::MaxwellUniformData) * Maxwell::MaxShaderStage;
  300. u8* buffer_ptr;
  301. GLintptr buffer_offset;
  302. std::tie(buffer_ptr, buffer_offset) =
  303. stream_buffer->Map(static_cast<GLsizeiptr>(buffer_size), 4);
  304. u8* offseted_buffer;
  305. std::tie(offseted_buffer, buffer_offset) = SetupVertexArrays(buffer_ptr, buffer_offset);
  306. offseted_buffer =
  307. reinterpret_cast<u8*>(Common::AlignUp(reinterpret_cast<size_t>(offseted_buffer), 4));
  308. buffer_offset = Common::AlignUp<size_t>(buffer_offset, 4);
  309. // If indexed mode, copy the index buffer
  310. GLintptr index_buffer_offset = 0;
  311. if (is_indexed) {
  312. const auto& memory_manager = Core::System().GetInstance().GPU().memory_manager;
  313. const boost::optional<VAddr> index_data_addr{
  314. memory_manager->GpuToCpuAddress(regs.index_array.StartAddress())};
  315. Memory::ReadBlock(*index_data_addr, offseted_buffer, index_buffer_size);
  316. index_buffer_offset = buffer_offset;
  317. offseted_buffer += index_buffer_size;
  318. buffer_offset += index_buffer_size;
  319. }
  320. offseted_buffer =
  321. reinterpret_cast<u8*>(Common::AlignUp(reinterpret_cast<size_t>(offseted_buffer), 4));
  322. buffer_offset = Common::AlignUp<size_t>(buffer_offset, 4);
  323. SetupShaders(offseted_buffer, buffer_offset);
  324. stream_buffer->Unmap();
  325. shader_program_manager->ApplyTo(state);
  326. state.Apply();
  327. const GLenum primitive_mode{MaxwellToGL::PrimitiveTopology(regs.draw.topology)};
  328. if (is_indexed) {
  329. const GLint base_vertex{static_cast<GLint>(regs.vb_element_base)};
  330. // Adjust the index buffer offset so it points to the first desired index.
  331. index_buffer_offset += regs.index_array.first * regs.index_array.FormatSizeInBytes();
  332. glDrawElementsBaseVertex(primitive_mode, regs.index_array.count,
  333. MaxwellToGL::IndexFormat(regs.index_array.format),
  334. reinterpret_cast<const void*>(index_buffer_offset), base_vertex);
  335. } else {
  336. glDrawArrays(primitive_mode, regs.vertex_buffer.first, regs.vertex_buffer.count);
  337. }
  338. // Disable scissor test
  339. state.scissor.enabled = false;
  340. accelerate_draw = AccelDraw::Disabled;
  341. // Unbind textures for potential future use as framebuffer attachments
  342. for (auto& texture_unit : state.texture_units) {
  343. texture_unit.Unbind();
  344. }
  345. state.Apply();
  346. // Mark framebuffer surfaces as dirty
  347. if (color_surface != nullptr && write_color_fb) {
  348. res_cache.MarkSurfaceAsDirty(color_surface);
  349. }
  350. if (depth_surface != nullptr && write_depth_fb) {
  351. res_cache.MarkSurfaceAsDirty(depth_surface);
  352. }
  353. }
  354. void RasterizerOpenGL::NotifyMaxwellRegisterChanged(u32 method) {}
  355. void RasterizerOpenGL::FlushAll() {
  356. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  357. res_cache.FlushRegion(0, Kernel::VMManager::MAX_ADDRESS);
  358. }
  359. void RasterizerOpenGL::FlushRegion(Tegra::GPUVAddr addr, u64 size) {
  360. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  361. res_cache.FlushRegion(addr, size);
  362. }
  363. void RasterizerOpenGL::InvalidateRegion(Tegra::GPUVAddr addr, u64 size) {
  364. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  365. res_cache.InvalidateRegion(addr, size);
  366. }
  367. void RasterizerOpenGL::FlushAndInvalidateRegion(Tegra::GPUVAddr addr, u64 size) {
  368. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  369. res_cache.FlushRegion(addr, size);
  370. res_cache.InvalidateRegion(addr, size);
  371. }
  372. bool RasterizerOpenGL::AccelerateDisplayTransfer(const void* config) {
  373. MICROPROFILE_SCOPE(OpenGL_Blits);
  374. UNREACHABLE();
  375. return true;
  376. }
  377. bool RasterizerOpenGL::AccelerateTextureCopy(const void* config) {
  378. UNREACHABLE();
  379. return true;
  380. }
  381. bool RasterizerOpenGL::AccelerateFill(const void* config) {
  382. UNREACHABLE();
  383. return true;
  384. }
  385. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  386. VAddr framebuffer_addr, u32 pixel_stride,
  387. ScreenInfo& screen_info) {
  388. if (!framebuffer_addr) {
  389. return {};
  390. }
  391. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  392. const auto& surface{res_cache.TryFindFramebufferSurface(framebuffer_addr)};
  393. if (!surface) {
  394. return {};
  395. }
  396. // Verify that the cached surface is the same size and format as the requested framebuffer
  397. const auto& params{surface->GetSurfaceParams()};
  398. const auto& pixel_format{SurfaceParams::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  399. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  400. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  401. ASSERT_MSG(params.pixel_format == pixel_format, "Framebuffer pixel_format is different");
  402. screen_info.display_texture = surface->Texture().handle;
  403. return true;
  404. }
  405. void RasterizerOpenGL::SamplerInfo::Create() {
  406. sampler.Create();
  407. mag_filter = min_filter = Tegra::Texture::TextureFilter::Linear;
  408. wrap_u = wrap_v = Tegra::Texture::WrapMode::Wrap;
  409. border_color_r = border_color_g = border_color_b = border_color_a = 0;
  410. // default is GL_LINEAR_MIPMAP_LINEAR
  411. glSamplerParameteri(sampler.handle, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  412. // Other attributes have correct defaults
  413. }
  414. void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntry& config) {
  415. GLuint s = sampler.handle;
  416. if (mag_filter != config.mag_filter) {
  417. mag_filter = config.mag_filter;
  418. glSamplerParameteri(s, GL_TEXTURE_MAG_FILTER, MaxwellToGL::TextureFilterMode(mag_filter));
  419. }
  420. if (min_filter != config.min_filter) {
  421. min_filter = config.min_filter;
  422. glSamplerParameteri(s, GL_TEXTURE_MIN_FILTER, MaxwellToGL::TextureFilterMode(min_filter));
  423. }
  424. if (wrap_u != config.wrap_u) {
  425. wrap_u = config.wrap_u;
  426. glSamplerParameteri(s, GL_TEXTURE_WRAP_S, MaxwellToGL::WrapMode(wrap_u));
  427. }
  428. if (wrap_v != config.wrap_v) {
  429. wrap_v = config.wrap_v;
  430. glSamplerParameteri(s, GL_TEXTURE_WRAP_T, MaxwellToGL::WrapMode(wrap_v));
  431. }
  432. if (wrap_u == Tegra::Texture::WrapMode::Border || wrap_v == Tegra::Texture::WrapMode::Border) {
  433. // TODO(Subv): Implement border color
  434. ASSERT(false);
  435. }
  436. }
  437. u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, GLuint program,
  438. u32 current_bindpoint,
  439. const std::vector<GLShader::ConstBufferEntry>& entries) {
  440. auto& gpu = Core::System::GetInstance().GPU();
  441. auto& maxwell3d = gpu.Get3DEngine();
  442. ASSERT_MSG(maxwell3d.IsShaderStageEnabled(stage),
  443. "Attempted to upload constbuffer of disabled shader stage");
  444. // Reset all buffer draw state for this stage.
  445. for (auto& buffer : state.draw.const_buffers[static_cast<size_t>(stage)]) {
  446. buffer.bindpoint = 0;
  447. buffer.enabled = false;
  448. }
  449. // Upload only the enabled buffers from the 16 constbuffers of each shader stage
  450. auto& shader_stage = maxwell3d.state.shader_stages[static_cast<size_t>(stage)];
  451. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  452. const auto& used_buffer = entries[bindpoint];
  453. const auto& buffer = shader_stage.const_buffers[used_buffer.GetIndex()];
  454. auto& buffer_draw_state =
  455. state.draw.const_buffers[static_cast<size_t>(stage)][used_buffer.GetIndex()];
  456. ASSERT_MSG(buffer.enabled, "Attempted to upload disabled constbuffer");
  457. buffer_draw_state.enabled = true;
  458. buffer_draw_state.bindpoint = current_bindpoint + bindpoint;
  459. boost::optional<VAddr> addr = gpu.memory_manager->GpuToCpuAddress(buffer.address);
  460. size_t size = 0;
  461. if (used_buffer.IsIndirect()) {
  462. // Buffer is accessed indirectly, so upload the entire thing
  463. size = buffer.size * sizeof(float);
  464. if (size > MaxConstbufferSize) {
  465. NGLOG_ERROR(HW_GPU, "indirect constbuffer size {} exceeds maximum {}", size,
  466. MaxConstbufferSize);
  467. size = MaxConstbufferSize;
  468. }
  469. } else {
  470. // Buffer is accessed directly, upload just what we use
  471. size = used_buffer.GetSize() * sizeof(float);
  472. }
  473. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  474. // UBO alignment requirements.
  475. size = Common::AlignUp(size, sizeof(GLvec4));
  476. ASSERT_MSG(size <= MaxConstbufferSize, "Constbuffer too big");
  477. std::vector<u8> data(size);
  478. Memory::ReadBlock(*addr, data.data(), data.size());
  479. glBindBuffer(GL_UNIFORM_BUFFER, buffer_draw_state.ssbo);
  480. glBufferData(GL_UNIFORM_BUFFER, data.size(), data.data(), GL_DYNAMIC_DRAW);
  481. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  482. // Now configure the bindpoint of the buffer inside the shader
  483. std::string buffer_name = used_buffer.GetName();
  484. GLuint index = glGetProgramResourceIndex(program, GL_UNIFORM_BLOCK, buffer_name.c_str());
  485. if (index != -1)
  486. glUniformBlockBinding(program, index, buffer_draw_state.bindpoint);
  487. }
  488. state.Apply();
  489. return current_bindpoint + static_cast<u32>(entries.size());
  490. }
  491. u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, GLuint program, u32 current_unit,
  492. const std::vector<GLShader::SamplerEntry>& entries) {
  493. auto& gpu = Core::System::GetInstance().GPU();
  494. auto& maxwell3d = gpu.Get3DEngine();
  495. ASSERT_MSG(maxwell3d.IsShaderStageEnabled(stage),
  496. "Attempted to upload textures of disabled shader stage");
  497. ASSERT_MSG(current_unit + entries.size() <= std::size(state.texture_units),
  498. "Exceeded the number of active textures.");
  499. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  500. const auto& entry = entries[bindpoint];
  501. u32 current_bindpoint = current_unit + bindpoint;
  502. // Bind the uniform to the sampler.
  503. GLint uniform = glGetUniformLocation(program, entry.GetName().c_str());
  504. ASSERT(uniform != -1);
  505. glProgramUniform1i(program, uniform, current_bindpoint);
  506. const auto texture = maxwell3d.GetStageTexture(entry.GetStage(), entry.GetOffset());
  507. if (!texture.enabled) {
  508. state.texture_units[current_bindpoint].texture_2d = 0;
  509. continue;
  510. }
  511. texture_samplers[current_bindpoint].SyncWithConfig(texture.tsc);
  512. Surface surface = res_cache.GetTextureSurface(texture);
  513. if (surface != nullptr) {
  514. state.texture_units[current_bindpoint].texture_2d = surface->Texture().handle;
  515. state.texture_units[current_bindpoint].swizzle.r =
  516. MaxwellToGL::SwizzleSource(texture.tic.x_source);
  517. state.texture_units[current_bindpoint].swizzle.g =
  518. MaxwellToGL::SwizzleSource(texture.tic.y_source);
  519. state.texture_units[current_bindpoint].swizzle.b =
  520. MaxwellToGL::SwizzleSource(texture.tic.z_source);
  521. state.texture_units[current_bindpoint].swizzle.a =
  522. MaxwellToGL::SwizzleSource(texture.tic.w_source);
  523. } else {
  524. // Can occur when texture addr is null or its memory is unmapped/invalid
  525. state.texture_units[current_bindpoint].texture_2d = 0;
  526. }
  527. }
  528. state.Apply();
  529. return current_unit + static_cast<u32>(entries.size());
  530. }
  531. void RasterizerOpenGL::BindFramebufferSurfaces(const Surface& color_surface,
  532. const Surface& depth_surface, bool has_stencil) {
  533. state.draw.draw_framebuffer = framebuffer.handle;
  534. state.Apply();
  535. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
  536. color_surface != nullptr ? color_surface->Texture().handle : 0, 0);
  537. if (depth_surface != nullptr) {
  538. if (has_stencil) {
  539. // attach both depth and stencil
  540. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
  541. depth_surface->Texture().handle, 0);
  542. } else {
  543. // attach depth
  544. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
  545. depth_surface->Texture().handle, 0);
  546. // clear stencil attachment
  547. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
  548. }
  549. } else {
  550. // clear both depth and stencil attachment
  551. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0,
  552. 0);
  553. }
  554. }
  555. void RasterizerOpenGL::SyncViewport(const MathUtil::Rectangle<u32>& surfaces_rect) {
  556. const auto& regs = Core::System().GetInstance().GPU().Maxwell3D().regs;
  557. const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[0].GetRect()};
  558. state.viewport.x = static_cast<GLint>(surfaces_rect.left) + viewport_rect.left;
  559. state.viewport.y = static_cast<GLint>(surfaces_rect.bottom) + viewport_rect.bottom;
  560. state.viewport.width = static_cast<GLsizei>(viewport_rect.GetWidth());
  561. state.viewport.height = static_cast<GLsizei>(viewport_rect.GetHeight());
  562. }
  563. void RasterizerOpenGL::SyncClipEnabled() {
  564. UNREACHABLE();
  565. }
  566. void RasterizerOpenGL::SyncClipCoef() {
  567. UNREACHABLE();
  568. }
  569. void RasterizerOpenGL::SyncCullMode() {
  570. UNREACHABLE();
  571. }
  572. void RasterizerOpenGL::SyncDepthScale() {
  573. UNREACHABLE();
  574. }
  575. void RasterizerOpenGL::SyncDepthOffset() {
  576. UNREACHABLE();
  577. }
  578. void RasterizerOpenGL::SyncBlendState() {
  579. const auto& regs = Core::System().GetInstance().GPU().Maxwell3D().regs;
  580. // TODO(Subv): Support more than just render target 0.
  581. state.blend.enabled = regs.blend.enable[0] != 0;
  582. if (!state.blend.enabled)
  583. return;
  584. ASSERT_MSG(regs.independent_blend_enable == 1, "Only independent blending is implemented");
  585. ASSERT_MSG(!regs.independent_blend[0].separate_alpha, "Unimplemented");
  586. state.blend.rgb_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_rgb);
  587. state.blend.src_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_rgb);
  588. state.blend.dst_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_rgb);
  589. state.blend.a_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_a);
  590. state.blend.src_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_a);
  591. state.blend.dst_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_a);
  592. }