gl_rasterizer.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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 <array>
  6. #include <bitset>
  7. #include <memory>
  8. #include <string>
  9. #include <string_view>
  10. #include <tuple>
  11. #include <utility>
  12. #include <glad/glad.h>
  13. #include "common/alignment.h"
  14. #include "common/assert.h"
  15. #include "common/logging/log.h"
  16. #include "common/math_util.h"
  17. #include "common/microprofile.h"
  18. #include "common/scope_exit.h"
  19. #include "core/core.h"
  20. #include "core/hle/kernel/process.h"
  21. #include "core/settings.h"
  22. #include "video_core/engines/kepler_compute.h"
  23. #include "video_core/engines/maxwell_3d.h"
  24. #include "video_core/memory_manager.h"
  25. #include "video_core/renderer_opengl/gl_rasterizer.h"
  26. #include "video_core/renderer_opengl/gl_shader_cache.h"
  27. #include "video_core/renderer_opengl/gl_shader_gen.h"
  28. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  29. #include "video_core/renderer_opengl/renderer_opengl.h"
  30. namespace OpenGL {
  31. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  32. using VideoCore::Surface::PixelFormat;
  33. using VideoCore::Surface::SurfaceTarget;
  34. using VideoCore::Surface::SurfaceType;
  35. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Format Setup", MP_RGB(128, 128, 192));
  36. MICROPROFILE_DEFINE(OpenGL_VB, "OpenGL", "Vertex Buffer Setup", MP_RGB(128, 128, 192));
  37. MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192));
  38. MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192));
  39. MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192));
  40. MICROPROFILE_DEFINE(OpenGL_Texture, "OpenGL", "Texture Setup", MP_RGB(128, 128, 192));
  41. MICROPROFILE_DEFINE(OpenGL_Framebuffer, "OpenGL", "Framebuffer Setup", MP_RGB(128, 128, 192));
  42. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  43. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
  44. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
  45. MICROPROFILE_DEFINE(OpenGL_PrimitiveAssembly, "OpenGL", "Prim Asmbl", MP_RGB(255, 100, 100));
  46. struct DrawParameters {
  47. GLenum primitive_mode;
  48. GLsizei count;
  49. GLint current_instance;
  50. bool use_indexed;
  51. GLint vertex_first;
  52. GLenum index_format;
  53. GLint base_vertex;
  54. GLintptr index_buffer_offset;
  55. void DispatchDraw() const {
  56. if (use_indexed) {
  57. const auto index_buffer_ptr = reinterpret_cast<const void*>(index_buffer_offset);
  58. if (current_instance > 0) {
  59. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, count, index_format,
  60. index_buffer_ptr, 1, base_vertex,
  61. current_instance);
  62. } else {
  63. glDrawElementsBaseVertex(primitive_mode, count, index_format, index_buffer_ptr,
  64. base_vertex);
  65. }
  66. } else {
  67. if (current_instance > 0) {
  68. glDrawArraysInstancedBaseInstance(primitive_mode, vertex_first, count, 1,
  69. current_instance);
  70. } else {
  71. glDrawArrays(primitive_mode, vertex_first, count);
  72. }
  73. }
  74. }
  75. };
  76. static std::size_t GetConstBufferSize(const Tegra::Engines::ConstBufferInfo& buffer,
  77. const GLShader::ConstBufferEntry& entry) {
  78. if (!entry.IsIndirect()) {
  79. return entry.GetSize();
  80. }
  81. if (buffer.size > Maxwell::MaxConstBufferSize) {
  82. LOG_WARNING(Render_OpenGL, "Indirect constbuffer size {} exceeds maximum {}", buffer.size,
  83. Maxwell::MaxConstBufferSize);
  84. return Maxwell::MaxConstBufferSize;
  85. }
  86. return buffer.size;
  87. }
  88. RasterizerOpenGL::RasterizerOpenGL(Core::System& system, Core::Frontend::EmuWindow& emu_window,
  89. ScreenInfo& info)
  90. : texture_cache{system, *this, device}, shader_cache{*this, system, emu_window, device},
  91. system{system}, screen_info{info}, buffer_cache{*this, system, STREAM_BUFFER_SIZE} {
  92. OpenGLState::ApplyDefaultState();
  93. shader_program_manager = std::make_unique<GLShader::ProgramManager>();
  94. state.draw.shader_program = 0;
  95. state.Apply();
  96. clear_framebuffer.Create();
  97. LOG_DEBUG(Render_OpenGL, "Sync fixed function OpenGL state here");
  98. CheckExtensions();
  99. }
  100. RasterizerOpenGL::~RasterizerOpenGL() {}
  101. void RasterizerOpenGL::CheckExtensions() {
  102. if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
  103. LOG_WARNING(
  104. Render_OpenGL,
  105. "Anisotropic filter is not supported! This can cause graphical issues in some games.");
  106. }
  107. }
  108. GLuint RasterizerOpenGL::SetupVertexFormat() {
  109. auto& gpu = system.GPU().Maxwell3D();
  110. const auto& regs = gpu.regs;
  111. if (!gpu.dirty.vertex_attrib_format) {
  112. return state.draw.vertex_array;
  113. }
  114. gpu.dirty.vertex_attrib_format = false;
  115. MICROPROFILE_SCOPE(OpenGL_VAO);
  116. auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
  117. auto& vao_entry = iter->second;
  118. if (is_cache_miss) {
  119. vao_entry.Create();
  120. const GLuint vao = vao_entry.handle;
  121. // Eventhough we are using DSA to create this vertex array, there is a bug on Intel's blob
  122. // that fails to properly create the vertex array if it's not bound even after creating it
  123. // with glCreateVertexArrays
  124. state.draw.vertex_array = vao;
  125. state.ApplyVertexArrayState();
  126. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
  127. // Enables the first 16 vertex attributes always, as we don't know which ones are actually
  128. // used until shader time. Note, Tegra technically supports 32, but we're capping this to 16
  129. // for now to avoid OpenGL errors.
  130. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  131. // assume every shader uses them all.
  132. for (u32 index = 0; index < 16; ++index) {
  133. const auto& attrib = regs.vertex_attrib_format[index];
  134. // Ignore invalid attributes.
  135. if (!attrib.IsValid())
  136. continue;
  137. const auto& buffer = regs.vertex_array[attrib.buffer];
  138. LOG_TRACE(Render_OpenGL,
  139. "vertex attrib {}, count={}, size={}, type={}, offset={}, normalize={}",
  140. index, attrib.ComponentCount(), attrib.SizeString(), attrib.TypeString(),
  141. attrib.offset.Value(), attrib.IsNormalized());
  142. ASSERT(buffer.IsEnabled());
  143. glEnableVertexArrayAttrib(vao, index);
  144. if (attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::SignedInt ||
  145. attrib.type ==
  146. Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::UnsignedInt) {
  147. glVertexArrayAttribIFormat(vao, index, attrib.ComponentCount(),
  148. MaxwellToGL::VertexType(attrib), attrib.offset);
  149. } else {
  150. glVertexArrayAttribFormat(
  151. vao, index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
  152. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  153. }
  154. glVertexArrayAttribBinding(vao, index, attrib.buffer);
  155. }
  156. }
  157. // Rebinding the VAO invalidates the vertex buffer bindings.
  158. gpu.dirty.ResetVertexArrays();
  159. state.draw.vertex_array = vao_entry.handle;
  160. return vao_entry.handle;
  161. }
  162. void RasterizerOpenGL::SetupVertexBuffer(GLuint vao) {
  163. auto& gpu = system.GPU().Maxwell3D();
  164. if (!gpu.dirty.vertex_array_buffers)
  165. return;
  166. gpu.dirty.vertex_array_buffers = false;
  167. const auto& regs = gpu.regs;
  168. MICROPROFILE_SCOPE(OpenGL_VB);
  169. // Upload all guest vertex arrays sequentially to our buffer
  170. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  171. if (!gpu.dirty.vertex_array[index])
  172. continue;
  173. gpu.dirty.vertex_array[index] = false;
  174. gpu.dirty.vertex_instance[index] = false;
  175. const auto& vertex_array = regs.vertex_array[index];
  176. if (!vertex_array.IsEnabled())
  177. continue;
  178. const GPUVAddr start = vertex_array.StartAddress();
  179. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  180. ASSERT(end > start);
  181. const u64 size = end - start + 1;
  182. const auto [vertex_buffer, vertex_buffer_offset] = buffer_cache.UploadMemory(start, size);
  183. // Bind the vertex array to the buffer at the current offset.
  184. vertex_array_pushbuffer.SetVertexBuffer(index, vertex_buffer, vertex_buffer_offset,
  185. vertex_array.stride);
  186. if (regs.instanced_arrays.IsInstancingEnabled(index) && vertex_array.divisor != 0) {
  187. // Enable vertex buffer instancing with the specified divisor.
  188. glVertexArrayBindingDivisor(vao, index, vertex_array.divisor);
  189. } else {
  190. // Disable the vertex buffer instancing.
  191. glVertexArrayBindingDivisor(vao, index, 0);
  192. }
  193. }
  194. }
  195. void RasterizerOpenGL::SetupVertexInstances(GLuint vao) {
  196. auto& gpu = system.GPU().Maxwell3D();
  197. if (!gpu.dirty.vertex_instances)
  198. return;
  199. gpu.dirty.vertex_instances = false;
  200. const auto& regs = gpu.regs;
  201. // Upload all guest vertex arrays sequentially to our buffer
  202. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  203. if (!gpu.dirty.vertex_instance[index])
  204. continue;
  205. gpu.dirty.vertex_instance[index] = false;
  206. if (regs.instanced_arrays.IsInstancingEnabled(index) &&
  207. regs.vertex_array[index].divisor != 0) {
  208. // Enable vertex buffer instancing with the specified divisor.
  209. glVertexArrayBindingDivisor(vao, index, regs.vertex_array[index].divisor);
  210. } else {
  211. // Disable the vertex buffer instancing.
  212. glVertexArrayBindingDivisor(vao, index, 0);
  213. }
  214. }
  215. }
  216. GLintptr RasterizerOpenGL::SetupIndexBuffer() {
  217. if (accelerate_draw != AccelDraw::Indexed) {
  218. return 0;
  219. }
  220. MICROPROFILE_SCOPE(OpenGL_Index);
  221. const auto& regs = system.GPU().Maxwell3D().regs;
  222. const std::size_t size = CalculateIndexBufferSize();
  223. const auto [buffer, offset] = buffer_cache.UploadMemory(regs.index_array.IndexStart(), size);
  224. vertex_array_pushbuffer.SetIndexBuffer(buffer);
  225. return offset;
  226. }
  227. DrawParameters RasterizerOpenGL::SetupDraw(GLintptr index_buffer_offset) {
  228. const auto& gpu = system.GPU().Maxwell3D();
  229. const auto& regs = gpu.regs;
  230. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  231. DrawParameters params{};
  232. params.current_instance = gpu.state.current_instance;
  233. params.use_indexed = is_indexed;
  234. params.primitive_mode = MaxwellToGL::PrimitiveTopology(regs.draw.topology);
  235. if (is_indexed) {
  236. params.index_format = MaxwellToGL::IndexFormat(regs.index_array.format);
  237. params.count = regs.index_array.count;
  238. params.index_buffer_offset = index_buffer_offset;
  239. params.base_vertex = static_cast<GLint>(regs.vb_element_base);
  240. } else {
  241. params.count = regs.vertex_buffer.count;
  242. params.vertex_first = regs.vertex_buffer.first;
  243. }
  244. return params;
  245. }
  246. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  247. MICROPROFILE_SCOPE(OpenGL_Shader);
  248. auto& gpu = system.GPU().Maxwell3D();
  249. BaseBindings base_bindings;
  250. std::array<bool, Maxwell::NumClipDistances> clip_distances{};
  251. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  252. const auto& shader_config = gpu.regs.shader_config[index];
  253. const Maxwell::ShaderProgram program{static_cast<Maxwell::ShaderProgram>(index)};
  254. // Skip stages that are not enabled
  255. if (!gpu.regs.IsShaderConfigEnabled(index)) {
  256. switch (program) {
  257. case Maxwell::ShaderProgram::Geometry:
  258. shader_program_manager->UseTrivialGeometryShader();
  259. break;
  260. default:
  261. break;
  262. }
  263. continue;
  264. }
  265. const std::size_t stage{index == 0 ? 0 : index - 1}; // Stage indices are 0 - 5
  266. GLShader::MaxwellUniformData ubo{};
  267. ubo.SetFromRegs(gpu, stage);
  268. const auto [buffer, offset] =
  269. buffer_cache.UploadHostMemory(&ubo, sizeof(ubo), device.GetUniformBufferAlignment());
  270. // Bind the emulation info buffer
  271. bind_ubo_pushbuffer.Push(buffer, offset, static_cast<GLsizeiptr>(sizeof(ubo)));
  272. Shader shader{shader_cache.GetStageProgram(program)};
  273. const auto stage_enum = static_cast<Maxwell::ShaderStage>(stage);
  274. SetupDrawConstBuffers(stage_enum, shader);
  275. SetupDrawGlobalMemory(stage_enum, shader);
  276. const auto texture_buffer_usage{SetupDrawTextures(stage_enum, shader, base_bindings)};
  277. const ProgramVariant variant{base_bindings, primitive_mode, texture_buffer_usage};
  278. const auto [program_handle, next_bindings] = shader->GetProgramHandle(variant);
  279. switch (program) {
  280. case Maxwell::ShaderProgram::VertexA:
  281. case Maxwell::ShaderProgram::VertexB:
  282. shader_program_manager->UseProgrammableVertexShader(program_handle);
  283. break;
  284. case Maxwell::ShaderProgram::Geometry:
  285. shader_program_manager->UseProgrammableGeometryShader(program_handle);
  286. break;
  287. case Maxwell::ShaderProgram::Fragment:
  288. shader_program_manager->UseProgrammableFragmentShader(program_handle);
  289. break;
  290. default:
  291. UNIMPLEMENTED_MSG("Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  292. shader_config.enable.Value(), shader_config.offset);
  293. }
  294. // Workaround for Intel drivers.
  295. // When a clip distance is enabled but not set in the shader it crops parts of the screen
  296. // (sometimes it's half the screen, sometimes three quarters). To avoid this, enable the
  297. // clip distances only when it's written by a shader stage.
  298. for (std::size_t i = 0; i < Maxwell::NumClipDistances; ++i) {
  299. clip_distances[i] = clip_distances[i] || shader->GetShaderEntries().clip_distances[i];
  300. }
  301. // When VertexA is enabled, we have dual vertex shaders
  302. if (program == Maxwell::ShaderProgram::VertexA) {
  303. // VertexB was combined with VertexA, so we skip the VertexB iteration
  304. index++;
  305. }
  306. base_bindings = next_bindings;
  307. }
  308. SyncClipEnabled(clip_distances);
  309. gpu.dirty.shaders = false;
  310. }
  311. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  312. const auto& regs = system.GPU().Maxwell3D().regs;
  313. std::size_t size = 0;
  314. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  315. if (!regs.vertex_array[index].IsEnabled())
  316. continue;
  317. const GPUVAddr start = regs.vertex_array[index].StartAddress();
  318. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  319. ASSERT(end > start);
  320. size += end - start + 1;
  321. }
  322. return size;
  323. }
  324. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  325. const auto& regs = system.GPU().Maxwell3D().regs;
  326. return static_cast<std::size_t>(regs.index_array.count) *
  327. static_cast<std::size_t>(regs.index_array.FormatSizeInBytes());
  328. }
  329. bool RasterizerOpenGL::AccelerateDrawBatch(bool is_indexed) {
  330. accelerate_draw = is_indexed ? AccelDraw::Indexed : AccelDraw::Arrays;
  331. DrawArrays();
  332. return true;
  333. }
  334. template <typename Map, typename Interval>
  335. static constexpr auto RangeFromInterval(Map& map, const Interval& interval) {
  336. return boost::make_iterator_range(map.equal_range(interval));
  337. }
  338. void RasterizerOpenGL::UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {
  339. const u64 page_start{addr >> Memory::PAGE_BITS};
  340. const u64 page_end{(addr + size + Memory::PAGE_SIZE - 1) >> Memory::PAGE_BITS};
  341. // Interval maps will erase segments if count reaches 0, so if delta is negative we have to
  342. // subtract after iterating
  343. const auto pages_interval = CachedPageMap::interval_type::right_open(page_start, page_end);
  344. if (delta > 0)
  345. cached_pages.add({pages_interval, delta});
  346. for (const auto& pair : RangeFromInterval(cached_pages, pages_interval)) {
  347. const auto interval = pair.first & pages_interval;
  348. const int count = pair.second;
  349. const VAddr interval_start_addr = boost::icl::first(interval) << Memory::PAGE_BITS;
  350. const VAddr interval_end_addr = boost::icl::last_next(interval) << Memory::PAGE_BITS;
  351. const u64 interval_size = interval_end_addr - interval_start_addr;
  352. if (delta > 0 && count == delta)
  353. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, true);
  354. else if (delta < 0 && count == -delta)
  355. Memory::RasterizerMarkRegionCached(interval_start_addr, interval_size, false);
  356. else
  357. ASSERT(count >= 0);
  358. }
  359. if (delta < 0)
  360. cached_pages.add({pages_interval, delta});
  361. }
  362. void RasterizerOpenGL::LoadDiskResources(const std::atomic_bool& stop_loading,
  363. const VideoCore::DiskResourceLoadCallback& callback) {
  364. shader_cache.LoadDiskCache(stop_loading, callback);
  365. }
  366. std::pair<bool, bool> RasterizerOpenGL::ConfigureFramebuffers(
  367. OpenGLState& current_state, bool using_color_fb, bool using_depth_fb, bool preserve_contents,
  368. std::optional<std::size_t> single_color_target) {
  369. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  370. auto& gpu = system.GPU().Maxwell3D();
  371. const auto& regs = gpu.regs;
  372. const FramebufferConfigState fb_config_state{using_color_fb, using_depth_fb, preserve_contents,
  373. single_color_target};
  374. if (fb_config_state == current_framebuffer_config_state && !gpu.dirty.render_settings) {
  375. // Only skip if the previous ConfigureFramebuffers call was from the same kind (multiple or
  376. // single color targets). This is done because the guest registers may not change but the
  377. // host framebuffer may contain different attachments
  378. return current_depth_stencil_usage;
  379. }
  380. gpu.dirty.render_settings = false;
  381. current_framebuffer_config_state = fb_config_state;
  382. texture_cache.GuardRenderTargets(true);
  383. View depth_surface{};
  384. if (using_depth_fb) {
  385. depth_surface = texture_cache.GetDepthBufferSurface(preserve_contents);
  386. } else {
  387. texture_cache.SetEmptyDepthBuffer();
  388. }
  389. UNIMPLEMENTED_IF(regs.rt_separate_frag_data == 0);
  390. // Bind the framebuffer surfaces
  391. current_state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0;
  392. FramebufferCacheKey fbkey;
  393. if (using_color_fb) {
  394. if (single_color_target) {
  395. // Used when just a single color attachment is enabled, e.g. for clearing a color buffer
  396. View color_surface{
  397. texture_cache.GetColorBufferSurface(*single_color_target, preserve_contents)};
  398. if (color_surface) {
  399. // Assume that a surface will be written to if it is used as a framebuffer, even if
  400. // the shader doesn't actually write to it.
  401. texture_cache.MarkColorBufferInUse(*single_color_target);
  402. // Workaround for and issue in nvidia drivers
  403. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  404. state.framebuffer_srgb.enabled |= color_surface->GetSurfaceParams().srgb_conversion;
  405. }
  406. fbkey.is_single_buffer = true;
  407. fbkey.color_attachments[0] =
  408. GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target);
  409. fbkey.colors[0] = color_surface;
  410. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  411. if (index != *single_color_target) {
  412. texture_cache.SetEmptyColorBuffer(index);
  413. }
  414. }
  415. } else {
  416. // Multiple color attachments are enabled
  417. for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
  418. View color_surface{texture_cache.GetColorBufferSurface(index, preserve_contents)};
  419. if (color_surface) {
  420. // Assume that a surface will be written to if it is used as a framebuffer, even
  421. // if the shader doesn't actually write to it.
  422. texture_cache.MarkColorBufferInUse(index);
  423. // Enable sRGB only for supported formats
  424. // Workaround for and issue in nvidia drivers
  425. // https://devtalk.nvidia.com/default/topic/776591/opengl/gl_framebuffer_srgb-functions-incorrectly/
  426. state.framebuffer_srgb.enabled |=
  427. color_surface->GetSurfaceParams().srgb_conversion;
  428. }
  429. fbkey.color_attachments[index] =
  430. GL_COLOR_ATTACHMENT0 + regs.rt_control.GetMap(index);
  431. fbkey.colors[index] = color_surface;
  432. }
  433. fbkey.is_single_buffer = false;
  434. fbkey.colors_count = regs.rt_control.count;
  435. }
  436. } else {
  437. // No color attachments are enabled - leave them as zero
  438. fbkey.is_single_buffer = true;
  439. }
  440. if (depth_surface) {
  441. // Assume that a surface will be written to if it is used as a framebuffer, even if
  442. // the shader doesn't actually write to it.
  443. texture_cache.MarkDepthBufferInUse();
  444. fbkey.zeta = depth_surface;
  445. fbkey.stencil_enable = depth_surface->GetSurfaceParams().type == SurfaceType::DepthStencil;
  446. }
  447. texture_cache.GuardRenderTargets(false);
  448. current_state.draw.draw_framebuffer = framebuffer_cache.GetFramebuffer(fbkey);
  449. SyncViewport(current_state);
  450. return current_depth_stencil_usage = {static_cast<bool>(depth_surface), fbkey.stencil_enable};
  451. }
  452. void RasterizerOpenGL::ConfigureClearFramebuffer(OpenGLState& current_state, bool using_color_fb,
  453. bool using_depth_fb, bool using_stencil_fb) {
  454. auto& gpu = system.GPU().Maxwell3D();
  455. const auto& regs = gpu.regs;
  456. texture_cache.GuardRenderTargets(true);
  457. View color_surface{};
  458. if (using_color_fb) {
  459. color_surface = texture_cache.GetColorBufferSurface(regs.clear_buffers.RT, false);
  460. }
  461. View depth_surface{};
  462. if (using_depth_fb || using_stencil_fb) {
  463. depth_surface = texture_cache.GetDepthBufferSurface(false);
  464. }
  465. texture_cache.GuardRenderTargets(false);
  466. current_state.draw.draw_framebuffer = clear_framebuffer.handle;
  467. current_state.ApplyFramebufferState();
  468. if (color_surface) {
  469. color_surface->Attach(GL_COLOR_ATTACHMENT0, GL_DRAW_FRAMEBUFFER);
  470. } else {
  471. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
  472. }
  473. if (depth_surface) {
  474. const auto& params = depth_surface->GetSurfaceParams();
  475. switch (params.type) {
  476. case VideoCore::Surface::SurfaceType::Depth:
  477. depth_surface->Attach(GL_DEPTH_ATTACHMENT, GL_DRAW_FRAMEBUFFER);
  478. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
  479. break;
  480. case VideoCore::Surface::SurfaceType::DepthStencil:
  481. depth_surface->Attach(GL_DEPTH_STENCIL_ATTACHMENT, GL_DRAW_FRAMEBUFFER);
  482. break;
  483. default:
  484. UNIMPLEMENTED();
  485. }
  486. } else {
  487. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0,
  488. 0);
  489. }
  490. }
  491. void RasterizerOpenGL::Clear() {
  492. const auto& maxwell3d = system.GPU().Maxwell3D();
  493. if (!maxwell3d.ShouldExecute()) {
  494. return;
  495. }
  496. const auto& regs = maxwell3d.regs;
  497. bool use_color{};
  498. bool use_depth{};
  499. bool use_stencil{};
  500. OpenGLState prev_state{OpenGLState::GetCurState()};
  501. SCOPE_EXIT({
  502. prev_state.AllDirty();
  503. prev_state.Apply();
  504. });
  505. OpenGLState clear_state{OpenGLState::GetCurState()};
  506. clear_state.SetDefaultViewports();
  507. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  508. regs.clear_buffers.A) {
  509. use_color = true;
  510. }
  511. if (use_color) {
  512. clear_state.color_mask[0].red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
  513. clear_state.color_mask[0].green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
  514. clear_state.color_mask[0].blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
  515. clear_state.color_mask[0].alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
  516. }
  517. if (regs.clear_buffers.Z) {
  518. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  519. use_depth = true;
  520. // Always enable the depth write when clearing the depth buffer. The depth write mask is
  521. // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to
  522. // true.
  523. clear_state.depth.test_enabled = true;
  524. clear_state.depth.test_func = GL_ALWAYS;
  525. clear_state.depth.write_mask = GL_TRUE;
  526. }
  527. if (regs.clear_buffers.S) {
  528. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear stencil but buffer is not enabled!");
  529. use_stencil = true;
  530. clear_state.stencil.test_enabled = true;
  531. if (regs.clear_flags.stencil) {
  532. // Stencil affects the clear so fill it with the used masks
  533. clear_state.stencil.front.test_func = GL_ALWAYS;
  534. clear_state.stencil.front.test_mask = regs.stencil_front_func_mask;
  535. clear_state.stencil.front.action_stencil_fail = GL_KEEP;
  536. clear_state.stencil.front.action_depth_fail = GL_KEEP;
  537. clear_state.stencil.front.action_depth_pass = GL_KEEP;
  538. clear_state.stencil.front.write_mask = regs.stencil_front_mask;
  539. if (regs.stencil_two_side_enable) {
  540. clear_state.stencil.back.test_func = GL_ALWAYS;
  541. clear_state.stencil.back.test_mask = regs.stencil_back_func_mask;
  542. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  543. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  544. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  545. clear_state.stencil.back.write_mask = regs.stencil_back_mask;
  546. } else {
  547. clear_state.stencil.back.test_func = GL_ALWAYS;
  548. clear_state.stencil.back.test_mask = 0xFFFFFFFF;
  549. clear_state.stencil.back.write_mask = 0xFFFFFFFF;
  550. clear_state.stencil.back.action_stencil_fail = GL_KEEP;
  551. clear_state.stencil.back.action_depth_fail = GL_KEEP;
  552. clear_state.stencil.back.action_depth_pass = GL_KEEP;
  553. }
  554. }
  555. }
  556. if (!use_color && !use_depth && !use_stencil) {
  557. // No color surface nor depth/stencil surface are enabled
  558. return;
  559. }
  560. ConfigureClearFramebuffer(clear_state, use_color, use_depth, use_stencil);
  561. SyncViewport(clear_state);
  562. if (regs.clear_flags.scissor) {
  563. SyncScissorTest(clear_state);
  564. }
  565. if (regs.clear_flags.viewport) {
  566. clear_state.EmulateViewportWithScissor();
  567. }
  568. clear_state.AllDirty();
  569. clear_state.Apply();
  570. if (use_color) {
  571. glClearBufferfv(GL_COLOR, 0, regs.clear_color);
  572. }
  573. if (use_depth && use_stencil) {
  574. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  575. } else if (use_depth) {
  576. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  577. } else if (use_stencil) {
  578. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  579. }
  580. }
  581. void RasterizerOpenGL::DrawArrays() {
  582. if (accelerate_draw == AccelDraw::Disabled)
  583. return;
  584. MICROPROFILE_SCOPE(OpenGL_Drawing);
  585. auto& gpu = system.GPU().Maxwell3D();
  586. if (!gpu.ShouldExecute()) {
  587. return;
  588. }
  589. SyncColorMask();
  590. SyncFragmentColorClampState();
  591. SyncMultiSampleState();
  592. SyncDepthTestState();
  593. SyncStencilTestState();
  594. SyncBlendState();
  595. SyncLogicOpState();
  596. SyncCullMode();
  597. SyncPrimitiveRestart();
  598. SyncScissorTest(state);
  599. SyncTransformFeedback();
  600. SyncPointState();
  601. SyncPolygonOffset();
  602. SyncAlphaTest();
  603. // Draw the vertex batch
  604. const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
  605. std::size_t buffer_size = CalculateVertexArraysSize();
  606. // Add space for index buffer
  607. if (is_indexed) {
  608. buffer_size = Common::AlignUp(buffer_size, 4) + CalculateIndexBufferSize();
  609. }
  610. // Uniform space for the 5 shader stages
  611. buffer_size = Common::AlignUp<std::size_t>(buffer_size, 4) +
  612. (sizeof(GLShader::MaxwellUniformData) + device.GetUniformBufferAlignment()) *
  613. Maxwell::MaxShaderStage;
  614. // Add space for at least 18 constant buffers
  615. buffer_size += Maxwell::MaxConstBuffers *
  616. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  617. // Prepare the vertex array.
  618. buffer_cache.Map(buffer_size);
  619. // Prepare vertex array format.
  620. const GLuint vao = SetupVertexFormat();
  621. vertex_array_pushbuffer.Setup(vao);
  622. // Upload vertex and index data.
  623. SetupVertexBuffer(vao);
  624. SetupVertexInstances(vao);
  625. const GLintptr index_buffer_offset = SetupIndexBuffer();
  626. // Setup draw parameters. It will automatically choose what glDraw* method to use.
  627. const DrawParameters params = SetupDraw(index_buffer_offset);
  628. // Prepare packed bindings.
  629. bind_ubo_pushbuffer.Setup(0);
  630. bind_ssbo_pushbuffer.Setup(0);
  631. // Setup shaders and their used resources.
  632. texture_cache.GuardSamplers(true);
  633. SetupShaders(params.primitive_mode);
  634. texture_cache.GuardSamplers(false);
  635. ConfigureFramebuffers(state);
  636. // Signal the buffer cache that we are not going to upload more things.
  637. const bool invalidate = buffer_cache.Unmap();
  638. // Now that we are no longer uploading data, we can safely bind the buffers to OpenGL.
  639. vertex_array_pushbuffer.Bind();
  640. bind_ubo_pushbuffer.Bind();
  641. bind_ssbo_pushbuffer.Bind();
  642. if (invalidate) {
  643. // As all cached buffers are invalidated, we need to recheck their state.
  644. gpu.dirty.ResetVertexArrays();
  645. }
  646. shader_program_manager->ApplyTo(state);
  647. state.Apply();
  648. if (texture_cache.TextureBarrier()) {
  649. glTextureBarrier();
  650. }
  651. params.DispatchDraw();
  652. accelerate_draw = AccelDraw::Disabled;
  653. gpu.dirty.memory_general = false;
  654. }
  655. void RasterizerOpenGL::DispatchCompute(GPUVAddr code_addr) {
  656. if (!GLAD_GL_ARB_compute_variable_group_size) {
  657. LOG_ERROR(Render_OpenGL, "Compute is currently not supported on this device due to the "
  658. "lack of GL_ARB_compute_variable_group_size");
  659. return;
  660. }
  661. auto kernel = shader_cache.GetComputeKernel(code_addr);
  662. SetupComputeImages(kernel);
  663. const auto [program, next_bindings] = kernel->GetProgramHandle({});
  664. state.draw.shader_program = program;
  665. state.draw.program_pipeline = 0;
  666. const std::size_t buffer_size =
  667. Tegra::Engines::KeplerCompute::NumConstBuffers *
  668. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  669. buffer_cache.Map(buffer_size);
  670. bind_ubo_pushbuffer.Setup(0);
  671. bind_ssbo_pushbuffer.Setup(0);
  672. SetupComputeConstBuffers(kernel);
  673. SetupComputeGlobalMemory(kernel);
  674. // TODO(Rodrigo): Bind images and samplers
  675. buffer_cache.Unmap();
  676. bind_ubo_pushbuffer.Bind();
  677. bind_ssbo_pushbuffer.Bind();
  678. state.ApplyShaderProgram();
  679. state.ApplyProgramPipeline();
  680. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  681. glDispatchComputeGroupSizeARB(launch_desc.grid_dim_x, launch_desc.grid_dim_y,
  682. launch_desc.grid_dim_z, launch_desc.block_dim_x,
  683. launch_desc.block_dim_y, launch_desc.block_dim_z);
  684. }
  685. void RasterizerOpenGL::FlushAll() {}
  686. void RasterizerOpenGL::FlushRegion(CacheAddr addr, u64 size) {
  687. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  688. if (!addr || !size) {
  689. return;
  690. }
  691. texture_cache.FlushRegion(addr, size);
  692. buffer_cache.FlushRegion(addr, size);
  693. }
  694. void RasterizerOpenGL::InvalidateRegion(CacheAddr addr, u64 size) {
  695. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  696. if (!addr || !size) {
  697. return;
  698. }
  699. texture_cache.InvalidateRegion(addr, size);
  700. shader_cache.InvalidateRegion(addr, size);
  701. buffer_cache.InvalidateRegion(addr, size);
  702. }
  703. void RasterizerOpenGL::FlushAndInvalidateRegion(CacheAddr addr, u64 size) {
  704. if (Settings::values.use_accurate_gpu_emulation) {
  705. FlushRegion(addr, size);
  706. }
  707. InvalidateRegion(addr, size);
  708. }
  709. void RasterizerOpenGL::FlushCommands() {
  710. glFlush();
  711. }
  712. void RasterizerOpenGL::TickFrame() {
  713. buffer_cache.TickFrame();
  714. }
  715. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  716. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  717. const Tegra::Engines::Fermi2D::Config& copy_config) {
  718. MICROPROFILE_SCOPE(OpenGL_Blits);
  719. texture_cache.DoFermiCopy(src, dst, copy_config);
  720. return true;
  721. }
  722. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  723. VAddr framebuffer_addr, u32 pixel_stride) {
  724. if (!framebuffer_addr) {
  725. return {};
  726. }
  727. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  728. const auto surface{
  729. texture_cache.TryFindFramebufferSurface(Memory::GetPointer(framebuffer_addr))};
  730. if (!surface) {
  731. return {};
  732. }
  733. // Verify that the cached surface is the same size and format as the requested framebuffer
  734. const auto& params{surface->GetSurfaceParams()};
  735. const auto& pixel_format{
  736. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  737. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  738. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  739. if (params.pixel_format != pixel_format) {
  740. LOG_WARNING(Render_OpenGL, "Framebuffer pixel_format is different");
  741. }
  742. screen_info.display_texture = surface->GetTexture();
  743. return true;
  744. }
  745. void RasterizerOpenGL::SetupDrawConstBuffers(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
  746. const Shader& shader) {
  747. MICROPROFILE_SCOPE(OpenGL_UBO);
  748. const auto& stages = system.GPU().Maxwell3D().state.shader_stages;
  749. const auto& shader_stage = stages[static_cast<std::size_t>(stage)];
  750. for (const auto& entry : shader->GetShaderEntries().const_buffers) {
  751. const auto& buffer = shader_stage.const_buffers[entry.GetIndex()];
  752. SetupConstBuffer(buffer, entry);
  753. }
  754. }
  755. void RasterizerOpenGL::SetupComputeConstBuffers(const Shader& kernel) {
  756. MICROPROFILE_SCOPE(OpenGL_UBO);
  757. const auto& launch_desc = system.GPU().KeplerCompute().launch_description;
  758. for (const auto& entry : kernel->GetShaderEntries().const_buffers) {
  759. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  760. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  761. Tegra::Engines::ConstBufferInfo buffer;
  762. buffer.address = config.Address();
  763. buffer.size = config.size;
  764. buffer.enabled = mask[entry.GetIndex()];
  765. SetupConstBuffer(buffer, entry);
  766. }
  767. }
  768. void RasterizerOpenGL::SetupConstBuffer(const Tegra::Engines::ConstBufferInfo& buffer,
  769. const GLShader::ConstBufferEntry& entry) {
  770. if (!buffer.enabled) {
  771. // Set values to zero to unbind buffers
  772. bind_ubo_pushbuffer.Push(buffer_cache.GetEmptyBuffer(sizeof(float)), 0, sizeof(float));
  773. return;
  774. }
  775. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  776. // UBO alignment requirements.
  777. const std::size_t size = Common::AlignUp(GetConstBufferSize(buffer, entry), sizeof(GLvec4));
  778. const auto alignment = device.GetUniformBufferAlignment();
  779. const auto [cbuf, offset] = buffer_cache.UploadMemory(buffer.address, size, alignment);
  780. bind_ubo_pushbuffer.Push(cbuf, offset, size);
  781. }
  782. void RasterizerOpenGL::SetupDrawGlobalMemory(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
  783. const Shader& shader) {
  784. auto& gpu{system.GPU()};
  785. auto& memory_manager{gpu.MemoryManager()};
  786. const auto cbufs{gpu.Maxwell3D().state.shader_stages[static_cast<std::size_t>(stage)]};
  787. for (const auto& entry : shader->GetShaderEntries().global_memory_entries) {
  788. const auto addr{cbufs.const_buffers[entry.GetCbufIndex()].address + entry.GetCbufOffset()};
  789. const auto gpu_addr{memory_manager.Read<u64>(addr)};
  790. const auto size{memory_manager.Read<u32>(addr + 8)};
  791. SetupGlobalMemory(entry, gpu_addr, size);
  792. }
  793. }
  794. void RasterizerOpenGL::SetupComputeGlobalMemory(const Shader& kernel) {
  795. auto& gpu{system.GPU()};
  796. auto& memory_manager{gpu.MemoryManager()};
  797. const auto cbufs{gpu.KeplerCompute().launch_description.const_buffer_config};
  798. for (const auto& entry : kernel->GetShaderEntries().global_memory_entries) {
  799. const auto addr{cbufs[entry.GetCbufIndex()].Address() + entry.GetCbufOffset()};
  800. const auto gpu_addr{memory_manager.Read<u64>(addr)};
  801. const auto size{memory_manager.Read<u32>(addr + 8)};
  802. SetupGlobalMemory(entry, gpu_addr, size);
  803. }
  804. }
  805. void RasterizerOpenGL::SetupGlobalMemory(const GLShader::GlobalMemoryEntry& entry,
  806. GPUVAddr gpu_addr, std::size_t size) {
  807. const auto alignment{device.GetShaderStorageBufferAlignment()};
  808. const auto [ssbo, buffer_offset] =
  809. buffer_cache.UploadMemory(gpu_addr, size, alignment, entry.IsWritten());
  810. bind_ssbo_pushbuffer.Push(ssbo, buffer_offset, static_cast<GLsizeiptr>(size));
  811. }
  812. TextureBufferUsage RasterizerOpenGL::SetupDrawTextures(Maxwell::ShaderStage stage,
  813. const Shader& shader,
  814. BaseBindings base_bindings) {
  815. MICROPROFILE_SCOPE(OpenGL_Texture);
  816. const auto& gpu = system.GPU();
  817. const auto& maxwell3d = gpu.Maxwell3D();
  818. const auto& entries = shader->GetShaderEntries().samplers;
  819. ASSERT_MSG(base_bindings.sampler + entries.size() <= std::size(state.texture_units),
  820. "Exceeded the number of active textures.");
  821. TextureBufferUsage texture_buffer_usage{0};
  822. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  823. const auto& entry = entries[bindpoint];
  824. Tegra::Texture::FullTextureInfo texture;
  825. if (entry.IsBindless()) {
  826. const auto cbuf = entry.GetBindlessCBuf();
  827. Tegra::Texture::TextureHandle tex_handle;
  828. tex_handle.raw = maxwell3d.AccessConstBuffer32(stage, cbuf.first, cbuf.second);
  829. texture = maxwell3d.GetTextureInfo(tex_handle, entry.GetOffset());
  830. } else {
  831. texture = maxwell3d.GetStageTexture(stage, entry.GetOffset());
  832. }
  833. if (SetupTexture(shader, base_bindings.sampler + bindpoint, texture, entry)) {
  834. texture_buffer_usage.set(bindpoint);
  835. }
  836. }
  837. return texture_buffer_usage;
  838. }
  839. bool RasterizerOpenGL::SetupTexture(const Shader& shader, u32 binding,
  840. const Tegra::Texture::FullTextureInfo& texture,
  841. const GLShader::SamplerEntry& entry) {
  842. auto& unit{state.texture_units[binding]};
  843. unit.sampler = sampler_cache.GetSampler(texture.tsc);
  844. const auto view = texture_cache.GetTextureSurface(texture, entry);
  845. if (!view) {
  846. // Can occur when texture addr is null or its memory is unmapped/invalid
  847. unit.texture = 0;
  848. return false;
  849. }
  850. unit.texture = view->GetTexture();
  851. if (view->GetSurfaceParams().IsBuffer()) {
  852. return true;
  853. }
  854. // Apply swizzle to textures that are not buffers.
  855. view->ApplySwizzle(texture.tic.x_source, texture.tic.y_source, texture.tic.z_source,
  856. texture.tic.w_source);
  857. return false;
  858. }
  859. void RasterizerOpenGL::SetupComputeImages(const Shader& shader) {
  860. const auto& compute = system.GPU().KeplerCompute();
  861. const auto& entries = shader->GetShaderEntries().images;
  862. for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
  863. const auto& entry = entries[bindpoint];
  864. const auto texture = [&]() {
  865. if (!entry.IsBindless()) {
  866. return compute.GetTexture(entry.GetOffset());
  867. }
  868. const auto cbuf = entry.GetBindlessCBuf();
  869. Tegra::Texture::TextureHandle tex_handle;
  870. tex_handle.raw = compute.AccessConstBuffer32(cbuf.first, cbuf.second);
  871. return compute.GetTextureInfo(tex_handle, entry.GetOffset());
  872. }();
  873. UNIMPLEMENTED();
  874. }
  875. }
  876. void RasterizerOpenGL::SyncViewport(OpenGLState& current_state) {
  877. const auto& regs = system.GPU().Maxwell3D().regs;
  878. const bool geometry_shaders_enabled =
  879. regs.IsShaderConfigEnabled(static_cast<size_t>(Maxwell::ShaderProgram::Geometry));
  880. const std::size_t viewport_count =
  881. geometry_shaders_enabled ? Tegra::Engines::Maxwell3D::Regs::NumViewports : 1;
  882. for (std::size_t i = 0; i < viewport_count; i++) {
  883. auto& viewport = current_state.viewports[i];
  884. const auto& src = regs.viewports[i];
  885. const Common::Rectangle<s32> viewport_rect{regs.viewport_transform[i].GetRect()};
  886. viewport.x = viewport_rect.left;
  887. viewport.y = viewport_rect.bottom;
  888. viewport.width = viewport_rect.GetWidth();
  889. viewport.height = viewport_rect.GetHeight();
  890. viewport.depth_range_far = src.depth_range_far;
  891. viewport.depth_range_near = src.depth_range_near;
  892. }
  893. state.depth_clamp.far_plane = regs.view_volume_clip_control.depth_clamp_far != 0;
  894. state.depth_clamp.near_plane = regs.view_volume_clip_control.depth_clamp_near != 0;
  895. }
  896. void RasterizerOpenGL::SyncClipEnabled(
  897. const std::array<bool, Maxwell::Regs::NumClipDistances>& clip_mask) {
  898. const auto& regs = system.GPU().Maxwell3D().regs;
  899. const std::array<bool, Maxwell::Regs::NumClipDistances> reg_state{
  900. regs.clip_distance_enabled.c0 != 0, regs.clip_distance_enabled.c1 != 0,
  901. regs.clip_distance_enabled.c2 != 0, regs.clip_distance_enabled.c3 != 0,
  902. regs.clip_distance_enabled.c4 != 0, regs.clip_distance_enabled.c5 != 0,
  903. regs.clip_distance_enabled.c6 != 0, regs.clip_distance_enabled.c7 != 0};
  904. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  905. state.clip_distance[i] = reg_state[i] && clip_mask[i];
  906. }
  907. }
  908. void RasterizerOpenGL::SyncClipCoef() {
  909. UNIMPLEMENTED();
  910. }
  911. void RasterizerOpenGL::SyncCullMode() {
  912. auto& maxwell3d = system.GPU().Maxwell3D();
  913. const auto& regs = maxwell3d.regs;
  914. state.cull.enabled = regs.cull.enabled != 0;
  915. if (state.cull.enabled) {
  916. state.cull.front_face = MaxwellToGL::FrontFace(regs.cull.front_face);
  917. state.cull.mode = MaxwellToGL::CullFace(regs.cull.cull_face);
  918. const bool flip_triangles{regs.screen_y_control.triangle_rast_flip == 0 ||
  919. regs.viewport_transform[0].scale_y < 0.0f};
  920. // If the GPU is configured to flip the rasterized triangles, then we need to flip the
  921. // notion of front and back. Note: We flip the triangles when the value of the register is 0
  922. // because OpenGL already does it for us.
  923. if (flip_triangles) {
  924. if (state.cull.front_face == GL_CCW)
  925. state.cull.front_face = GL_CW;
  926. else if (state.cull.front_face == GL_CW)
  927. state.cull.front_face = GL_CCW;
  928. }
  929. }
  930. }
  931. void RasterizerOpenGL::SyncPrimitiveRestart() {
  932. const auto& regs = system.GPU().Maxwell3D().regs;
  933. state.primitive_restart.enabled = regs.primitive_restart.enabled;
  934. state.primitive_restart.index = regs.primitive_restart.index;
  935. }
  936. void RasterizerOpenGL::SyncDepthTestState() {
  937. const auto& regs = system.GPU().Maxwell3D().regs;
  938. state.depth.test_enabled = regs.depth_test_enable != 0;
  939. state.depth.write_mask = regs.depth_write_enabled ? GL_TRUE : GL_FALSE;
  940. if (!state.depth.test_enabled) {
  941. return;
  942. }
  943. state.depth.test_func = MaxwellToGL::ComparisonOp(regs.depth_test_func);
  944. }
  945. void RasterizerOpenGL::SyncStencilTestState() {
  946. auto& maxwell3d = system.GPU().Maxwell3D();
  947. if (!maxwell3d.dirty.stencil_test) {
  948. return;
  949. }
  950. maxwell3d.dirty.stencil_test = false;
  951. const auto& regs = maxwell3d.regs;
  952. state.stencil.test_enabled = regs.stencil_enable != 0;
  953. state.MarkDirtyStencilState();
  954. if (!regs.stencil_enable) {
  955. return;
  956. }
  957. state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func);
  958. state.stencil.front.test_ref = regs.stencil_front_func_ref;
  959. state.stencil.front.test_mask = regs.stencil_front_func_mask;
  960. state.stencil.front.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_fail);
  961. state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail);
  962. state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass);
  963. state.stencil.front.write_mask = regs.stencil_front_mask;
  964. if (regs.stencil_two_side_enable) {
  965. state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
  966. state.stencil.back.test_ref = regs.stencil_back_func_ref;
  967. state.stencil.back.test_mask = regs.stencil_back_func_mask;
  968. state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
  969. state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
  970. state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
  971. state.stencil.back.write_mask = regs.stencil_back_mask;
  972. } else {
  973. state.stencil.back.test_func = GL_ALWAYS;
  974. state.stencil.back.test_ref = 0;
  975. state.stencil.back.test_mask = 0xFFFFFFFF;
  976. state.stencil.back.write_mask = 0xFFFFFFFF;
  977. state.stencil.back.action_stencil_fail = GL_KEEP;
  978. state.stencil.back.action_depth_fail = GL_KEEP;
  979. state.stencil.back.action_depth_pass = GL_KEEP;
  980. }
  981. }
  982. void RasterizerOpenGL::SyncColorMask() {
  983. auto& maxwell3d = system.GPU().Maxwell3D();
  984. if (!maxwell3d.dirty.color_mask) {
  985. return;
  986. }
  987. const auto& regs = maxwell3d.regs;
  988. const std::size_t count =
  989. regs.independent_blend_enable ? Tegra::Engines::Maxwell3D::Regs::NumRenderTargets : 1;
  990. for (std::size_t i = 0; i < count; i++) {
  991. const auto& source = regs.color_mask[regs.color_mask_common ? 0 : i];
  992. auto& dest = state.color_mask[i];
  993. dest.red_enabled = (source.R == 0) ? GL_FALSE : GL_TRUE;
  994. dest.green_enabled = (source.G == 0) ? GL_FALSE : GL_TRUE;
  995. dest.blue_enabled = (source.B == 0) ? GL_FALSE : GL_TRUE;
  996. dest.alpha_enabled = (source.A == 0) ? GL_FALSE : GL_TRUE;
  997. }
  998. state.MarkDirtyColorMask();
  999. maxwell3d.dirty.color_mask = false;
  1000. }
  1001. void RasterizerOpenGL::SyncMultiSampleState() {
  1002. const auto& regs = system.GPU().Maxwell3D().regs;
  1003. state.multisample_control.alpha_to_coverage = regs.multisample_control.alpha_to_coverage != 0;
  1004. state.multisample_control.alpha_to_one = regs.multisample_control.alpha_to_one != 0;
  1005. }
  1006. void RasterizerOpenGL::SyncFragmentColorClampState() {
  1007. const auto& regs = system.GPU().Maxwell3D().regs;
  1008. state.fragment_color_clamp.enabled = regs.frag_color_clamp != 0;
  1009. }
  1010. void RasterizerOpenGL::SyncBlendState() {
  1011. auto& maxwell3d = system.GPU().Maxwell3D();
  1012. if (!maxwell3d.dirty.blend_state) {
  1013. return;
  1014. }
  1015. const auto& regs = maxwell3d.regs;
  1016. state.blend_color.red = regs.blend_color.r;
  1017. state.blend_color.green = regs.blend_color.g;
  1018. state.blend_color.blue = regs.blend_color.b;
  1019. state.blend_color.alpha = regs.blend_color.a;
  1020. state.independant_blend.enabled = regs.independent_blend_enable;
  1021. if (!state.independant_blend.enabled) {
  1022. auto& blend = state.blend[0];
  1023. const auto& src = regs.blend;
  1024. blend.enabled = src.enable[0] != 0;
  1025. if (blend.enabled) {
  1026. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  1027. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  1028. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  1029. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  1030. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  1031. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  1032. }
  1033. for (std::size_t i = 1; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  1034. state.blend[i].enabled = false;
  1035. }
  1036. maxwell3d.dirty.blend_state = false;
  1037. state.MarkDirtyBlendState();
  1038. return;
  1039. }
  1040. for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
  1041. auto& blend = state.blend[i];
  1042. const auto& src = regs.independent_blend[i];
  1043. blend.enabled = regs.blend.enable[i] != 0;
  1044. if (!blend.enabled)
  1045. continue;
  1046. blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
  1047. blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
  1048. blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
  1049. blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
  1050. blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
  1051. blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
  1052. }
  1053. state.MarkDirtyBlendState();
  1054. maxwell3d.dirty.blend_state = false;
  1055. }
  1056. void RasterizerOpenGL::SyncLogicOpState() {
  1057. const auto& regs = system.GPU().Maxwell3D().regs;
  1058. state.logic_op.enabled = regs.logic_op.enable != 0;
  1059. if (!state.logic_op.enabled)
  1060. return;
  1061. ASSERT_MSG(regs.blend.enable[0] == 0,
  1062. "Blending and logic op can't be enabled at the same time.");
  1063. state.logic_op.operation = MaxwellToGL::LogicOp(regs.logic_op.operation);
  1064. }
  1065. void RasterizerOpenGL::SyncScissorTest(OpenGLState& current_state) {
  1066. const auto& regs = system.GPU().Maxwell3D().regs;
  1067. const bool geometry_shaders_enabled =
  1068. regs.IsShaderConfigEnabled(static_cast<size_t>(Maxwell::ShaderProgram::Geometry));
  1069. const std::size_t viewport_count =
  1070. geometry_shaders_enabled ? Tegra::Engines::Maxwell3D::Regs::NumViewports : 1;
  1071. for (std::size_t i = 0; i < viewport_count; i++) {
  1072. const auto& src = regs.scissor_test[i];
  1073. auto& dst = current_state.viewports[i].scissor;
  1074. dst.enabled = (src.enable != 0);
  1075. if (dst.enabled == 0) {
  1076. return;
  1077. }
  1078. const u32 width = src.max_x - src.min_x;
  1079. const u32 height = src.max_y - src.min_y;
  1080. dst.x = src.min_x;
  1081. dst.y = src.min_y;
  1082. dst.width = width;
  1083. dst.height = height;
  1084. }
  1085. }
  1086. void RasterizerOpenGL::SyncTransformFeedback() {
  1087. const auto& regs = system.GPU().Maxwell3D().regs;
  1088. UNIMPLEMENTED_IF_MSG(regs.tfb_enabled != 0, "Transform feedbacks are not implemented");
  1089. }
  1090. void RasterizerOpenGL::SyncPointState() {
  1091. const auto& regs = system.GPU().Maxwell3D().regs;
  1092. // Limit the point size to 1 since nouveau sometimes sets a point size of 0 (and that's invalid
  1093. // in OpenGL).
  1094. state.point.size = std::max(1.0f, regs.point_size);
  1095. }
  1096. void RasterizerOpenGL::SyncPolygonOffset() {
  1097. auto& maxwell3d = system.GPU().Maxwell3D();
  1098. if (!maxwell3d.dirty.polygon_offset) {
  1099. return;
  1100. }
  1101. const auto& regs = maxwell3d.regs;
  1102. state.polygon_offset.fill_enable = regs.polygon_offset_fill_enable != 0;
  1103. state.polygon_offset.line_enable = regs.polygon_offset_line_enable != 0;
  1104. state.polygon_offset.point_enable = regs.polygon_offset_point_enable != 0;
  1105. state.polygon_offset.units = regs.polygon_offset_units;
  1106. state.polygon_offset.factor = regs.polygon_offset_factor;
  1107. state.polygon_offset.clamp = regs.polygon_offset_clamp;
  1108. state.MarkDirtyPolygonOffset();
  1109. maxwell3d.dirty.polygon_offset = false;
  1110. }
  1111. void RasterizerOpenGL::SyncAlphaTest() {
  1112. const auto& regs = system.GPU().Maxwell3D().regs;
  1113. UNIMPLEMENTED_IF_MSG(regs.alpha_test_enabled != 0 && regs.rt_control.count > 1,
  1114. "Alpha Testing is enabled with more than one rendertarget");
  1115. state.alpha_test.enabled = regs.alpha_test_enabled;
  1116. if (!state.alpha_test.enabled) {
  1117. return;
  1118. }
  1119. state.alpha_test.func = MaxwellToGL::ComparisonOp(regs.alpha_test_func);
  1120. state.alpha_test.ref = regs.alpha_test_ref;
  1121. }
  1122. } // namespace OpenGL