gl_rasterizer.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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 VBO, VAO and UBO
  68. vertex_buffer = OGLStreamBuffer::MakeBuffer(GLAD_GL_ARB_buffer_storage, GL_ARRAY_BUFFER);
  69. vertex_buffer->Create(VERTEX_BUFFER_SIZE, VERTEX_BUFFER_SIZE / 2);
  70. sw_vao.Create();
  71. uniform_buffer.Create();
  72. state.draw.vertex_array = sw_vao.handle;
  73. state.draw.vertex_buffer = vertex_buffer->GetHandle();
  74. state.draw.uniform_buffer = uniform_buffer.handle;
  75. state.Apply();
  76. // Create render framebuffer
  77. framebuffer.Create();
  78. hw_vao.Create();
  79. hw_vao_enabled_attributes.fill(false);
  80. stream_buffer = OGLStreamBuffer::MakeBuffer(has_ARB_buffer_storage, GL_ARRAY_BUFFER);
  81. stream_buffer->Create(STREAM_BUFFER_SIZE, STREAM_BUFFER_SIZE / 2);
  82. state.draw.vertex_buffer = stream_buffer->GetHandle();
  83. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  84. state.draw.shader_program = 0;
  85. state.draw.vertex_array = hw_vao.handle;
  86. state.Apply();
  87. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, stream_buffer->GetHandle());
  88. for (unsigned index = 0; index < uniform_buffers.size(); ++index) {
  89. auto& buffer = uniform_buffers[index];
  90. buffer.Create();
  91. glBindBuffer(GL_UNIFORM_BUFFER, buffer.handle);
  92. glBufferData(GL_UNIFORM_BUFFER, sizeof(GLShader::MaxwellUniformData), nullptr,
  93. GL_STREAM_COPY);
  94. glBindBufferBase(GL_UNIFORM_BUFFER, index, buffer.handle);
  95. }
  96. accelerate_draw = AccelDraw::Disabled;
  97. glEnable(GL_BLEND);
  98. LOG_CRITICAL(Render_OpenGL, "Sync fixed function OpenGL state here!");
  99. }
  100. RasterizerOpenGL::~RasterizerOpenGL() {
  101. if (stream_buffer != nullptr) {
  102. state.draw.vertex_buffer = stream_buffer->GetHandle();
  103. state.Apply();
  104. stream_buffer->Release();
  105. }
  106. }
  107. std::pair<u8*, GLintptr> RasterizerOpenGL::SetupVertexArrays(u8* array_ptr,
  108. GLintptr buffer_offset) {
  109. MICROPROFILE_SCOPE(OpenGL_VAO);
  110. const auto& regs = Core::System().GetInstance().GPU().Maxwell3D().regs;
  111. const auto& memory_manager = Core::System().GetInstance().GPU().memory_manager;
  112. state.draw.vertex_array = hw_vao.handle;
  113. state.draw.vertex_buffer = stream_buffer->GetHandle();
  114. state.Apply();
  115. // Upload all guest vertex arrays sequentially to our buffer
  116. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  117. const auto& vertex_array = regs.vertex_array[index];
  118. if (!vertex_array.IsEnabled())
  119. continue;
  120. const Tegra::GPUVAddr start = vertex_array.StartAddress();
  121. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  122. ASSERT(end > start);
  123. u64 size = end - start + 1;
  124. // Copy vertex array data
  125. res_cache.FlushRegion(start, size, nullptr);
  126. Memory::ReadBlock(*memory_manager->GpuToCpuAddress(start), array_ptr, size);
  127. // Bind the vertex array to the buffer at the current offset.
  128. glBindVertexBuffer(index, stream_buffer->GetHandle(), buffer_offset, vertex_array.stride);
  129. ASSERT_MSG(vertex_array.divisor == 0, "Vertex buffer divisor unimplemented");
  130. array_ptr += size;
  131. buffer_offset += size;
  132. }
  133. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  134. // Enables the first 16 vertex attributes always, as we don't know which ones are actually used
  135. // until shader time. Note, Tegra technically supports 32, but we're capping this to 16 for now
  136. // to avoid OpenGL errors.
  137. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  138. // assume every shader uses them all.
  139. for (unsigned index = 0; index < 16; ++index) {
  140. auto& attrib = regs.vertex_attrib_format[index];
  141. NGLOG_DEBUG(HW_GPU, "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  142. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  143. attrib.offset.Value(), attrib.IsNormalized());
  144. auto& buffer = regs.vertex_array[attrib.buffer];
  145. ASSERT(buffer.IsEnabled());
  146. glEnableVertexAttribArray(index);
  147. glVertexAttribFormat(index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  148. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  149. glVertexAttribBinding(index, attrib.buffer);
  150. hw_vao_enabled_attributes[index] = true;
  151. }
  152. return {array_ptr, buffer_offset};
  153. }
  154. void RasterizerOpenGL::SetupShaders(u8* buffer_ptr, GLintptr buffer_offset) {
  155. // Helper function for uploading uniform data
  156. const auto copy_buffer = [&](GLuint handle, GLintptr offset, GLsizeiptr size) {
  157. if (has_ARB_direct_state_access) {
  158. glCopyNamedBufferSubData(stream_buffer->GetHandle(), handle, offset, 0, size);
  159. } else {
  160. glBindBuffer(GL_COPY_WRITE_BUFFER, handle);
  161. glCopyBufferSubData(GL_ARRAY_BUFFER, GL_COPY_WRITE_BUFFER, offset, 0, size);
  162. }
  163. };
  164. auto& gpu = Core::System().GetInstance().GPU().Maxwell3D();
  165. ASSERT_MSG(!gpu.regs.shader_config[0].enable, "VertexA is unsupported!");
  166. // Next available bindpoint to use when uploading the const buffers to the GLSL shaders.
  167. u32 current_constbuffer_bindpoint = 0;
  168. for (unsigned index = 1; index < Maxwell::MaxShaderProgram; ++index) {
  169. auto& shader_config = gpu.regs.shader_config[index];
  170. const Maxwell::ShaderProgram program{static_cast<Maxwell::ShaderProgram>(index)};
  171. const auto& stage = index - 1; // Stage indices are 0 - 5
  172. const bool is_enabled = gpu.IsShaderStageEnabled(static_cast<Maxwell::ShaderStage>(stage));
  173. // Skip stages that are not enabled
  174. if (!is_enabled) {
  175. continue;
  176. }
  177. // Upload uniform data as one UBO per stage
  178. const GLintptr ubo_offset = buffer_offset;
  179. copy_buffer(uniform_buffers[stage].handle, ubo_offset,
  180. sizeof(GLShader::MaxwellUniformData));
  181. GLShader::MaxwellUniformData* ub_ptr =
  182. reinterpret_cast<GLShader::MaxwellUniformData*>(buffer_ptr);
  183. ub_ptr->SetFromRegs(gpu.state.shader_stages[stage]);
  184. buffer_ptr += sizeof(GLShader::MaxwellUniformData);
  185. buffer_offset += sizeof(GLShader::MaxwellUniformData);
  186. // Fetch program code from memory
  187. GLShader::ProgramCode program_code;
  188. const u64 gpu_address{gpu.regs.code_address.CodeAddress() + shader_config.offset};
  189. const boost::optional<VAddr> cpu_address{gpu.memory_manager.GpuToCpuAddress(gpu_address)};
  190. Memory::ReadBlock(*cpu_address, program_code.data(), program_code.size() * sizeof(u64));
  191. GLShader::ShaderSetup setup{std::move(program_code)};
  192. GLShader::ShaderEntries shader_resources;
  193. switch (program) {
  194. case Maxwell::ShaderProgram::VertexB: {
  195. GLShader::MaxwellVSConfig vs_config{setup};
  196. shader_resources =
  197. shader_program_manager->UseProgrammableVertexShader(vs_config, setup);
  198. break;
  199. }
  200. case Maxwell::ShaderProgram::Fragment: {
  201. GLShader::MaxwellFSConfig fs_config{setup};
  202. shader_resources =
  203. shader_program_manager->UseProgrammableFragmentShader(fs_config, setup);
  204. break;
  205. }
  206. default:
  207. LOG_CRITICAL(HW_GPU, "Unimplemented shader index=%d, enable=%d, offset=0x%08X", index,
  208. shader_config.enable.Value(), shader_config.offset);
  209. UNREACHABLE();
  210. }
  211. GLuint gl_stage_program = shader_program_manager->GetCurrentProgramStage(
  212. static_cast<Maxwell::ShaderStage>(stage));
  213. // Configure the const buffers for this shader stage.
  214. current_constbuffer_bindpoint =
  215. SetupConstBuffers(static_cast<Maxwell::ShaderStage>(stage), gl_stage_program,
  216. current_constbuffer_bindpoint, shader_resources.const_buffer_entries);
  217. }
  218. shader_program_manager->UseTrivialGeometryShader();
  219. }
  220. size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  221. const auto& regs = Core::System().GetInstance().GPU().Maxwell3D().regs;
  222. size_t size = 0;
  223. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  224. if (!regs.vertex_array[index].IsEnabled())
  225. continue;
  226. const Tegra::GPUVAddr start = regs.vertex_array[index].StartAddress();
  227. const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  228. ASSERT(end > start);
  229. size += end - start + 1;
  230. }
  231. return size;
  232. }
  233. bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
  234. accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
  235. DrawArrays();
  236. return true;
  237. }
  238. void RasterizerOpenGL::DrawArrays() {
  239. if (accelerate_draw == AccelDraw::Disabled)
  240. return;
  241. MICROPROFILE_SCOPE(OpenGL_Drawing);
  242. const auto& regs = Core::System().GetInstance().GPU().Maxwell3D().regs;
  243. // TODO(bunnei): Implement these
  244. const bool has_stencil = false;
  245. const bool using_color_fb = true;
  246. const bool using_depth_fb = false;
  247. const MathUtil::Rectangle<s32> viewport_rect{regs.viewport[0].GetRect()};
  248. const bool write_color_fb =
  249. state.color_mask.red_enabled == GL_TRUE || state.color_mask.green_enabled == GL_TRUE ||
  250. state.color_mask.blue_enabled == GL_TRUE || state.color_mask.alpha_enabled == GL_TRUE;
  251. const bool write_depth_fb =
  252. (state.depth.test_enabled && state.depth.write_mask == GL_TRUE) ||
  253. (has_stencil && state.stencil.test_enabled && state.stencil.write_mask != 0);
  254. Surface color_surface;
  255. Surface depth_surface;
  256. MathUtil::Rectangle<u32> surfaces_rect;
  257. std::tie(color_surface, depth_surface, surfaces_rect) =
  258. res_cache.GetFramebufferSurfaces(using_color_fb, using_depth_fb, viewport_rect);
  259. const u16 res_scale = color_surface != nullptr
  260. ? color_surface->res_scale
  261. : (depth_surface == nullptr ? 1u : depth_surface->res_scale);
  262. MathUtil::Rectangle<u32> draw_rect{
  263. static_cast<u32>(
  264. std::clamp<s32>(static_cast<s32>(surfaces_rect.left) + viewport_rect.left * res_scale,
  265. surfaces_rect.left, surfaces_rect.right)), // Left
  266. static_cast<u32>(
  267. std::clamp<s32>(static_cast<s32>(surfaces_rect.bottom) + viewport_rect.top * res_scale,
  268. surfaces_rect.bottom, surfaces_rect.top)), // Top
  269. static_cast<u32>(
  270. std::clamp<s32>(static_cast<s32>(surfaces_rect.left) + viewport_rect.right * res_scale,
  271. surfaces_rect.left, surfaces_rect.right)), // Right
  272. static_cast<u32>(std::clamp<s32>(static_cast<s32>(surfaces_rect.bottom) +
  273. viewport_rect.bottom * res_scale,
  274. surfaces_rect.bottom, surfaces_rect.top))}; // Bottom
  275. // Bind the framebuffer surfaces
  276. BindFramebufferSurfaces(color_surface, depth_surface, has_stencil);
  277. // Sync the viewport
  278. SyncViewport(surfaces_rect, res_scale);
  279. // TODO(bunnei): Sync framebuffer_scale uniform here
  280. // TODO(bunnei): Sync scissorbox uniform(s) here
  281. // Sync and bind the texture surfaces
  282. BindTextures();
  283. // Viewport can have negative offsets or larger dimensions than our framebuffer sub-rect. Enable
  284. // scissor test to prevent drawing outside of the framebuffer region
  285. state.scissor.enabled = true;
  286. state.scissor.x = draw_rect.left;
  287. state.scissor.y = draw_rect.bottom;
  288. state.scissor.width = draw_rect.GetWidth();
  289. state.scissor.height = draw_rect.GetHeight();
  290. state.Apply();
  291. // Draw the vertex batch
  292. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  293. const u64 index_buffer_size{regs.index_array.count * regs.index_array.FormatSizeInBytes()};
  294. const unsigned vertex_num{is_indexed ? regs.index_array.count : regs.vertex_buffer.count};
  295. state.draw.vertex_buffer = stream_buffer->GetHandle();
  296. state.Apply();
  297. size_t buffer_size = CalculateVertexArraysSize();
  298. if (is_indexed) {
  299. buffer_size = Common::AlignUp<size_t>(buffer_size, 4) + index_buffer_size;
  300. }
  301. // Uniform space for the 5 shader stages
  302. buffer_size = Common::AlignUp<size_t>(buffer_size, 4) +
  303. sizeof(GLShader::MaxwellUniformData) * Maxwell::MaxShaderStage;
  304. u8* buffer_ptr;
  305. GLintptr buffer_offset;
  306. std::tie(buffer_ptr, buffer_offset) =
  307. stream_buffer->Map(static_cast<GLsizeiptr>(buffer_size), 4);
  308. u8* offseted_buffer;
  309. std::tie(offseted_buffer, buffer_offset) = SetupVertexArrays(buffer_ptr, buffer_offset);
  310. offseted_buffer =
  311. reinterpret_cast<u8*>(Common::AlignUp(reinterpret_cast<size_t>(offseted_buffer), 4));
  312. buffer_offset = Common::AlignUp<size_t>(buffer_offset, 4);
  313. // If indexed mode, copy the index buffer
  314. GLintptr index_buffer_offset = 0;
  315. if (is_indexed) {
  316. const auto& memory_manager = Core::System().GetInstance().GPU().memory_manager;
  317. const boost::optional<VAddr> index_data_addr{
  318. memory_manager->GpuToCpuAddress(regs.index_array.StartAddress())};
  319. Memory::ReadBlock(*index_data_addr, offseted_buffer, index_buffer_size);
  320. index_buffer_offset = buffer_offset;
  321. offseted_buffer += index_buffer_size;
  322. buffer_offset += index_buffer_size;
  323. }
  324. offseted_buffer =
  325. reinterpret_cast<u8*>(Common::AlignUp(reinterpret_cast<size_t>(offseted_buffer), 4));
  326. buffer_offset = Common::AlignUp<size_t>(buffer_offset, 4);
  327. SetupShaders(offseted_buffer, buffer_offset);
  328. stream_buffer->Unmap();
  329. shader_program_manager->ApplyTo(state);
  330. state.Apply();
  331. const GLenum primitive_mode{MaxwellToGL::PrimitiveTopology(regs.draw.topology)};
  332. if (is_indexed) {
  333. const GLint index_min{static_cast<GLint>(regs.index_array.first)};
  334. const GLint index_max{static_cast<GLint>(regs.index_array.first + regs.index_array.count)};
  335. glDrawRangeElementsBaseVertex(primitive_mode, index_min, index_max, regs.index_array.count,
  336. MaxwellToGL::IndexFormat(regs.index_array.format),
  337. reinterpret_cast<const void*>(index_buffer_offset),
  338. -index_min);
  339. } else {
  340. glDrawArrays(primitive_mode, 0, regs.vertex_buffer.count);
  341. }
  342. // Disable scissor test
  343. state.scissor.enabled = false;
  344. accelerate_draw = AccelDraw::Disabled;
  345. // Unbind textures for potential future use as framebuffer attachments
  346. for (auto& texture_unit : state.texture_units) {
  347. texture_unit.texture_2d = 0;
  348. }
  349. state.Apply();
  350. // Mark framebuffer surfaces as dirty
  351. MathUtil::Rectangle<u32> draw_rect_unscaled{
  352. draw_rect.left / res_scale, draw_rect.top / res_scale, draw_rect.right / res_scale,
  353. draw_rect.bottom / res_scale};
  354. if (color_surface != nullptr && write_color_fb) {
  355. auto interval = color_surface->GetSubRectInterval(draw_rect_unscaled);
  356. res_cache.InvalidateRegion(boost::icl::first(interval), boost::icl::length(interval),
  357. color_surface);
  358. }
  359. if (depth_surface != nullptr && write_depth_fb) {
  360. auto interval = depth_surface->GetSubRectInterval(draw_rect_unscaled);
  361. res_cache.InvalidateRegion(boost::icl::first(interval), boost::icl::length(interval),
  362. depth_surface);
  363. }
  364. }
  365. void RasterizerOpenGL::BindTextures() {
  366. using Regs = Tegra::Engines::Maxwell3D::Regs;
  367. auto& maxwell3d = Core::System::GetInstance().GPU().Get3DEngine();
  368. // Each Maxwell shader stage can have an arbitrary number of textures, but we're limited to a
  369. // certain number in OpenGL. We try to only use the minimum amount of host textures by not
  370. // keeping a 1:1 relation between guest texture ids and host texture ids, ie, guest texture id 8
  371. // can be host texture id 0 if it's the only texture used in the guest shader program.
  372. u32 host_texture_index = 0;
  373. for (u32 stage = 0; stage < Regs::MaxShaderStage; ++stage) {
  374. ASSERT(host_texture_index < texture_samplers.size());
  375. const auto textures = maxwell3d.GetStageTextures(static_cast<Regs::ShaderStage>(stage));
  376. for (unsigned texture_index = 0; texture_index < textures.size(); ++texture_index) {
  377. const auto& texture = textures[texture_index];
  378. if (texture.enabled) {
  379. texture_samplers[host_texture_index].SyncWithConfig(texture.tsc);
  380. Surface surface = res_cache.GetTextureSurface(texture);
  381. if (surface != nullptr) {
  382. state.texture_units[host_texture_index].texture_2d = surface->texture.handle;
  383. } else {
  384. // Can occur when texture addr is null or its memory is unmapped/invalid
  385. state.texture_units[texture_index].texture_2d = 0;
  386. }
  387. ++host_texture_index;
  388. } else {
  389. state.texture_units[texture_index].texture_2d = 0;
  390. }
  391. }
  392. }
  393. }
  394. void RasterizerOpenGL::NotifyMaxwellRegisterChanged(u32 method) {
  395. const auto& regs = Core::System().GetInstance().GPU().Maxwell3D().regs;
  396. switch (method) {
  397. case MAXWELL3D_REG_INDEX(blend.separate_alpha):
  398. ASSERT_MSG(false, "unimplemented");
  399. break;
  400. case MAXWELL3D_REG_INDEX(blend.equation_rgb):
  401. state.blend.rgb_equation = MaxwellToGL::BlendEquation(regs.blend.equation_rgb);
  402. break;
  403. case MAXWELL3D_REG_INDEX(blend.factor_source_rgb):
  404. state.blend.src_rgb_func = MaxwellToGL::BlendFunc(regs.blend.factor_source_rgb);
  405. break;
  406. case MAXWELL3D_REG_INDEX(blend.factor_dest_rgb):
  407. state.blend.dst_rgb_func = MaxwellToGL::BlendFunc(regs.blend.factor_dest_rgb);
  408. break;
  409. case MAXWELL3D_REG_INDEX(blend.equation_a):
  410. state.blend.a_equation = MaxwellToGL::BlendEquation(regs.blend.equation_a);
  411. break;
  412. case MAXWELL3D_REG_INDEX(blend.factor_source_a):
  413. state.blend.src_a_func = MaxwellToGL::BlendFunc(regs.blend.factor_source_a);
  414. break;
  415. case MAXWELL3D_REG_INDEX(blend.factor_dest_a):
  416. state.blend.dst_a_func = MaxwellToGL::BlendFunc(regs.blend.factor_dest_a);
  417. break;
  418. }
  419. }
  420. void RasterizerOpenGL::FlushAll() {
  421. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  422. res_cache.FlushAll();
  423. }
  424. void RasterizerOpenGL::FlushRegion(Tegra::GPUVAddr addr, u64 size) {
  425. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  426. res_cache.FlushRegion(addr, size);
  427. }
  428. void RasterizerOpenGL::InvalidateRegion(Tegra::GPUVAddr addr, u64 size) {
  429. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  430. res_cache.InvalidateRegion(addr, size, nullptr);
  431. }
  432. void RasterizerOpenGL::FlushAndInvalidateRegion(Tegra::GPUVAddr addr, u64 size) {
  433. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  434. res_cache.FlushRegion(addr, size);
  435. res_cache.InvalidateRegion(addr, size, nullptr);
  436. }
  437. bool RasterizerOpenGL::AccelerateDisplayTransfer(const void* config) {
  438. MICROPROFILE_SCOPE(OpenGL_Blits);
  439. UNREACHABLE();
  440. return true;
  441. }
  442. bool RasterizerOpenGL::AccelerateTextureCopy(const void* config) {
  443. UNREACHABLE();
  444. return true;
  445. }
  446. bool RasterizerOpenGL::AccelerateFill(const void* config) {
  447. UNREACHABLE();
  448. return true;
  449. }
  450. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& framebuffer,
  451. VAddr framebuffer_addr, u32 pixel_stride,
  452. ScreenInfo& screen_info) {
  453. if (framebuffer_addr == 0) {
  454. return false;
  455. }
  456. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  457. SurfaceParams src_params;
  458. src_params.cpu_addr = framebuffer_addr;
  459. src_params.addr = res_cache.TryFindFramebufferGpuAddress(framebuffer_addr).get_value_or(0);
  460. src_params.width = std::min(framebuffer.width, pixel_stride);
  461. src_params.height = framebuffer.height;
  462. src_params.stride = pixel_stride;
  463. src_params.is_tiled = true;
  464. src_params.block_height = Tegra::Texture::TICEntry::DefaultBlockHeight;
  465. src_params.pixel_format =
  466. SurfaceParams::PixelFormatFromGPUPixelFormat(framebuffer.pixel_format);
  467. src_params.component_type =
  468. SurfaceParams::ComponentTypeFromGPUPixelFormat(framebuffer.pixel_format);
  469. src_params.UpdateParams();
  470. MathUtil::Rectangle<u32> src_rect;
  471. Surface src_surface;
  472. std::tie(src_surface, src_rect) =
  473. res_cache.GetSurfaceSubRect(src_params, ScaleMatch::Ignore, true);
  474. if (src_surface == nullptr) {
  475. return false;
  476. }
  477. u32 scaled_width = src_surface->GetScaledWidth();
  478. u32 scaled_height = src_surface->GetScaledHeight();
  479. screen_info.display_texcoords = MathUtil::Rectangle<float>(
  480. (float)src_rect.bottom / (float)scaled_height, (float)src_rect.left / (float)scaled_width,
  481. (float)src_rect.top / (float)scaled_height, (float)src_rect.right / (float)scaled_width);
  482. screen_info.display_texture = src_surface->texture.handle;
  483. return true;
  484. }
  485. void RasterizerOpenGL::SamplerInfo::Create() {
  486. sampler.Create();
  487. mag_filter = min_filter = Tegra::Texture::TextureFilter::Linear;
  488. wrap_u = wrap_v = Tegra::Texture::WrapMode::Wrap;
  489. border_color_r = border_color_g = border_color_b = border_color_a = 0;
  490. // default is GL_LINEAR_MIPMAP_LINEAR
  491. glSamplerParameteri(sampler.handle, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  492. // Other attributes have correct defaults
  493. }
  494. void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntry& config) {
  495. GLuint s = sampler.handle;
  496. if (mag_filter != config.mag_filter) {
  497. mag_filter = config.mag_filter;
  498. glSamplerParameteri(s, GL_TEXTURE_MAG_FILTER, MaxwellToGL::TextureFilterMode(mag_filter));
  499. }
  500. if (min_filter != config.min_filter) {
  501. min_filter = config.min_filter;
  502. glSamplerParameteri(s, GL_TEXTURE_MIN_FILTER, MaxwellToGL::TextureFilterMode(min_filter));
  503. }
  504. if (wrap_u != config.wrap_u) {
  505. wrap_u = config.wrap_u;
  506. glSamplerParameteri(s, GL_TEXTURE_WRAP_S, MaxwellToGL::WrapMode(wrap_u));
  507. }
  508. if (wrap_v != config.wrap_v) {
  509. wrap_v = config.wrap_v;
  510. glSamplerParameteri(s, GL_TEXTURE_WRAP_T, MaxwellToGL::WrapMode(wrap_v));
  511. }
  512. if (wrap_u == Tegra::Texture::WrapMode::Border || wrap_v == Tegra::Texture::WrapMode::Border) {
  513. // TODO(Subv): Implement border color
  514. ASSERT(false);
  515. }
  516. }
  517. u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, GLuint program,
  518. u32 current_bindpoint,
  519. const std::vector<GLShader::ConstBufferEntry>& entries) {
  520. auto& gpu = Core::System::GetInstance().GPU();
  521. auto& maxwell3d = gpu.Get3DEngine();
  522. ASSERT_MSG(maxwell3d.IsShaderStageEnabled(stage),
  523. "Attempted to upload constbuffer of disabled shader stage");
  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. 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. ASSERT_MSG(buffer.enabled, "Attempted to upload disabled constbuffer");
  537. buffer_draw_state.enabled = true;
  538. buffer_draw_state.bindpoint = current_bindpoint + bindpoint;
  539. boost::optional<VAddr> addr = gpu.memory_manager->GpuToCpuAddress(buffer.address);
  540. std::vector<u8> data(used_buffer.GetSize() * sizeof(float));
  541. Memory::ReadBlock(*addr, data.data(), data.size());
  542. glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer_draw_state.ssbo);
  543. glBufferData(GL_SHADER_STORAGE_BUFFER, data.size(), data.data(), GL_DYNAMIC_DRAW);
  544. glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
  545. // Now configure the bindpoint of the buffer inside the shader
  546. std::string buffer_name = used_buffer.GetName();
  547. GLuint index =
  548. glGetProgramResourceIndex(program, GL_SHADER_STORAGE_BLOCK, buffer_name.c_str());
  549. if (index != -1)
  550. glShaderStorageBlockBinding(program, index, buffer_draw_state.bindpoint);
  551. }
  552. state.Apply();
  553. return current_bindpoint + entries.size();
  554. }
  555. void RasterizerOpenGL::BindFramebufferSurfaces(const Surface& color_surface,
  556. const Surface& depth_surface, bool has_stencil) {
  557. state.draw.draw_framebuffer = framebuffer.handle;
  558. state.Apply();
  559. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
  560. color_surface != nullptr ? color_surface->texture.handle : 0, 0);
  561. if (depth_surface != nullptr) {
  562. if (has_stencil) {
  563. // attach both depth and stencil
  564. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
  565. depth_surface->texture.handle, 0);
  566. } else {
  567. // attach depth
  568. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
  569. depth_surface->texture.handle, 0);
  570. // clear stencil attachment
  571. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
  572. }
  573. } else {
  574. // clear both depth and stencil attachment
  575. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0,
  576. 0);
  577. }
  578. }
  579. void RasterizerOpenGL::SyncViewport(const MathUtil::Rectangle<u32>& surfaces_rect, u16 res_scale) {
  580. const auto& regs = Core::System().GetInstance().GPU().Maxwell3D().regs;
  581. const MathUtil::Rectangle<s32> viewport_rect{regs.viewport[0].GetRect()};
  582. state.viewport.x = static_cast<GLint>(surfaces_rect.left) + viewport_rect.left * res_scale;
  583. state.viewport.y = static_cast<GLint>(surfaces_rect.bottom) + viewport_rect.bottom * res_scale;
  584. state.viewport.width = static_cast<GLsizei>(viewport_rect.GetWidth() * res_scale);
  585. state.viewport.height = static_cast<GLsizei>(viewport_rect.GetHeight() * res_scale);
  586. }
  587. void RasterizerOpenGL::SyncClipEnabled() {
  588. UNREACHABLE();
  589. }
  590. void RasterizerOpenGL::SyncClipCoef() {
  591. UNREACHABLE();
  592. }
  593. void RasterizerOpenGL::SyncCullMode() {
  594. UNREACHABLE();
  595. }
  596. void RasterizerOpenGL::SyncDepthScale() {
  597. UNREACHABLE();
  598. }
  599. void RasterizerOpenGL::SyncDepthOffset() {
  600. UNREACHABLE();
  601. }
  602. void RasterizerOpenGL::SyncBlendEnabled() {
  603. UNREACHABLE();
  604. }
  605. void RasterizerOpenGL::SyncBlendFuncs() {
  606. UNREACHABLE();
  607. }
  608. void RasterizerOpenGL::SyncBlendColor() {
  609. UNREACHABLE();
  610. }