gl_rasterizer.cpp 37 KB

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