gl_rasterizer.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721
  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/memory.h"
  22. #include "core/settings.h"
  23. #include "video_core/engines/kepler_compute.h"
  24. #include "video_core/engines/maxwell_3d.h"
  25. #include "video_core/engines/shader_type.h"
  26. #include "video_core/memory_manager.h"
  27. #include "video_core/renderer_opengl/gl_query_cache.h"
  28. #include "video_core/renderer_opengl/gl_rasterizer.h"
  29. #include "video_core/renderer_opengl/gl_shader_cache.h"
  30. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  31. #include "video_core/renderer_opengl/renderer_opengl.h"
  32. #include "video_core/shader_cache.h"
  33. namespace OpenGL {
  34. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  35. using Tegra::Engines::ShaderType;
  36. using VideoCore::Surface::PixelFormat;
  37. using VideoCore::Surface::SurfaceTarget;
  38. using VideoCore::Surface::SurfaceType;
  39. MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Format Setup", MP_RGB(128, 128, 192));
  40. MICROPROFILE_DEFINE(OpenGL_VB, "OpenGL", "Vertex Buffer Setup", MP_RGB(128, 128, 192));
  41. MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192));
  42. MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192));
  43. MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192));
  44. MICROPROFILE_DEFINE(OpenGL_Texture, "OpenGL", "Texture Setup", MP_RGB(128, 128, 192));
  45. MICROPROFILE_DEFINE(OpenGL_Framebuffer, "OpenGL", "Framebuffer Setup", MP_RGB(128, 128, 192));
  46. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  47. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
  48. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100));
  49. MICROPROFILE_DEFINE(OpenGL_PrimitiveAssembly, "OpenGL", "Prim Asmbl", MP_RGB(255, 100, 100));
  50. namespace {
  51. constexpr std::size_t NUM_CONST_BUFFERS_PER_STAGE = 18;
  52. constexpr std::size_t NUM_CONST_BUFFERS_BYTES_PER_STAGE =
  53. NUM_CONST_BUFFERS_PER_STAGE * Maxwell::MaxConstBufferSize;
  54. constexpr std::size_t TOTAL_CONST_BUFFER_BYTES =
  55. NUM_CONST_BUFFERS_BYTES_PER_STAGE * Maxwell::MaxShaderStage;
  56. constexpr std::size_t NUM_SUPPORTED_VERTEX_ATTRIBUTES = 16;
  57. constexpr std::size_t NUM_SUPPORTED_VERTEX_BINDINGS = 16;
  58. template <typename Engine, typename Entry>
  59. Tegra::Texture::FullTextureInfo GetTextureInfo(const Engine& engine, const Entry& entry,
  60. ShaderType shader_type, std::size_t index = 0) {
  61. if constexpr (std::is_same_v<Entry, SamplerEntry>) {
  62. if (entry.is_separated) {
  63. const u32 buffer_1 = entry.buffer;
  64. const u32 buffer_2 = entry.secondary_buffer;
  65. const u32 offset_1 = entry.offset;
  66. const u32 offset_2 = entry.secondary_offset;
  67. const u32 handle_1 = engine.AccessConstBuffer32(shader_type, buffer_1, offset_1);
  68. const u32 handle_2 = engine.AccessConstBuffer32(shader_type, buffer_2, offset_2);
  69. return engine.GetTextureInfo(handle_1 | handle_2);
  70. }
  71. }
  72. if (entry.is_bindless) {
  73. const u32 handle = engine.AccessConstBuffer32(shader_type, entry.buffer, entry.offset);
  74. return engine.GetTextureInfo(handle);
  75. }
  76. const auto& gpu_profile = engine.AccessGuestDriverProfile();
  77. const u32 offset = entry.offset + static_cast<u32>(index * gpu_profile.GetTextureHandlerSize());
  78. if constexpr (std::is_same_v<Engine, Tegra::Engines::Maxwell3D>) {
  79. return engine.GetStageTexture(shader_type, offset);
  80. } else {
  81. return engine.GetTexture(offset);
  82. }
  83. }
  84. std::size_t GetConstBufferSize(const Tegra::Engines::ConstBufferInfo& buffer,
  85. const ConstBufferEntry& entry) {
  86. if (!entry.IsIndirect()) {
  87. return entry.GetSize();
  88. }
  89. if (buffer.size > Maxwell::MaxConstBufferSize) {
  90. LOG_WARNING(Render_OpenGL, "Indirect constbuffer size {} exceeds maximum {}", buffer.size,
  91. Maxwell::MaxConstBufferSize);
  92. return Maxwell::MaxConstBufferSize;
  93. }
  94. return buffer.size;
  95. }
  96. /// Translates hardware transform feedback indices
  97. /// @param location Hardware location
  98. /// @return Pair of ARB_transform_feedback3 token stream first and third arguments
  99. /// @note Read https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_transform_feedback3.txt
  100. std::pair<GLint, GLint> TransformFeedbackEnum(u8 location) {
  101. const u8 index = location / 4;
  102. if (index >= 8 && index <= 39) {
  103. return {GL_GENERIC_ATTRIB_NV, index - 8};
  104. }
  105. if (index >= 48 && index <= 55) {
  106. return {GL_TEXTURE_COORD_NV, index - 48};
  107. }
  108. switch (index) {
  109. case 7:
  110. return {GL_POSITION, 0};
  111. case 40:
  112. return {GL_PRIMARY_COLOR_NV, 0};
  113. case 41:
  114. return {GL_SECONDARY_COLOR_NV, 0};
  115. case 42:
  116. return {GL_BACK_PRIMARY_COLOR_NV, 0};
  117. case 43:
  118. return {GL_BACK_SECONDARY_COLOR_NV, 0};
  119. }
  120. UNIMPLEMENTED_MSG("index={}", static_cast<int>(index));
  121. return {GL_POSITION, 0};
  122. }
  123. void oglEnable(GLenum cap, bool state) {
  124. (state ? glEnable : glDisable)(cap);
  125. }
  126. void UpdateBindlessSSBOs(GLenum target, const BindlessSSBO* ssbos, size_t num_ssbos) {
  127. if (num_ssbos == 0) {
  128. return;
  129. }
  130. glProgramLocalParametersI4uivNV(target, 0, static_cast<GLsizei>(num_ssbos),
  131. reinterpret_cast<const GLuint*>(ssbos));
  132. }
  133. } // Anonymous namespace
  134. RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& emu_window, Tegra::GPU& gpu_,
  135. Core::Memory::Memory& cpu_memory, const Device& device_,
  136. ScreenInfo& screen_info_, ProgramManager& program_manager_,
  137. StateTracker& state_tracker_)
  138. : RasterizerAccelerated{cpu_memory}, gpu(gpu_), maxwell3d(gpu.Maxwell3D()),
  139. kepler_compute(gpu.KeplerCompute()), gpu_memory(gpu.MemoryManager()), device(device_),
  140. screen_info(screen_info_), program_manager(program_manager_), state_tracker(state_tracker_),
  141. texture_cache(*this, maxwell3d, gpu_memory, device, state_tracker),
  142. shader_cache(*this, emu_window, gpu, maxwell3d, kepler_compute, gpu_memory, device),
  143. query_cache(*this, maxwell3d, gpu_memory),
  144. buffer_cache(*this, gpu_memory, cpu_memory, device, STREAM_BUFFER_SIZE),
  145. fence_manager(*this, gpu, texture_cache, buffer_cache, query_cache),
  146. async_shaders(emu_window) {
  147. CheckExtensions();
  148. unified_uniform_buffer.Create();
  149. glNamedBufferStorage(unified_uniform_buffer.handle, TOTAL_CONST_BUFFER_BYTES, nullptr, 0);
  150. if (device.UseAssemblyShaders()) {
  151. glCreateBuffers(static_cast<GLsizei>(staging_cbufs.size()), staging_cbufs.data());
  152. for (const GLuint cbuf : staging_cbufs) {
  153. glNamedBufferStorage(cbuf, static_cast<GLsizeiptr>(Maxwell::MaxConstBufferSize),
  154. nullptr, 0);
  155. }
  156. }
  157. if (device.UseAsynchronousShaders()) {
  158. async_shaders.AllocateWorkers();
  159. }
  160. }
  161. RasterizerOpenGL::~RasterizerOpenGL() {
  162. if (device.UseAssemblyShaders()) {
  163. glDeleteBuffers(static_cast<GLsizei>(staging_cbufs.size()), staging_cbufs.data());
  164. }
  165. }
  166. void RasterizerOpenGL::CheckExtensions() {
  167. if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
  168. LOG_WARNING(
  169. Render_OpenGL,
  170. "Anisotropic filter is not supported! This can cause graphical issues in some games.");
  171. }
  172. }
  173. void RasterizerOpenGL::SetupVertexFormat() {
  174. auto& flags = maxwell3d.dirty.flags;
  175. if (!flags[Dirty::VertexFormats]) {
  176. return;
  177. }
  178. flags[Dirty::VertexFormats] = false;
  179. MICROPROFILE_SCOPE(OpenGL_VAO);
  180. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL. Enables
  181. // the first 16 vertex attributes always, as we don't know which ones are actually used until
  182. // shader time. Note, Tegra technically supports 32, but we're capping this to 16 for now to
  183. // avoid OpenGL errors.
  184. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  185. // assume every shader uses them all.
  186. for (std::size_t index = 0; index < NUM_SUPPORTED_VERTEX_ATTRIBUTES; ++index) {
  187. if (!flags[Dirty::VertexFormat0 + index]) {
  188. continue;
  189. }
  190. flags[Dirty::VertexFormat0 + index] = false;
  191. const auto attrib = maxwell3d.regs.vertex_attrib_format[index];
  192. const auto gl_index = static_cast<GLuint>(index);
  193. // Disable constant attributes.
  194. if (attrib.IsConstant()) {
  195. glDisableVertexAttribArray(gl_index);
  196. continue;
  197. }
  198. glEnableVertexAttribArray(gl_index);
  199. if (attrib.type == Maxwell::VertexAttribute::Type::SignedInt ||
  200. attrib.type == Maxwell::VertexAttribute::Type::UnsignedInt) {
  201. glVertexAttribIFormat(gl_index, attrib.ComponentCount(),
  202. MaxwellToGL::VertexFormat(attrib), attrib.offset);
  203. } else {
  204. glVertexAttribFormat(gl_index, attrib.ComponentCount(),
  205. MaxwellToGL::VertexFormat(attrib),
  206. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  207. }
  208. glVertexAttribBinding(gl_index, attrib.buffer);
  209. }
  210. }
  211. void RasterizerOpenGL::SetupVertexBuffer() {
  212. auto& flags = maxwell3d.dirty.flags;
  213. if (!flags[Dirty::VertexBuffers]) {
  214. return;
  215. }
  216. flags[Dirty::VertexBuffers] = false;
  217. MICROPROFILE_SCOPE(OpenGL_VB);
  218. const bool use_unified_memory = device.HasVertexBufferUnifiedMemory();
  219. // Upload all guest vertex arrays sequentially to our buffer
  220. const auto& regs = maxwell3d.regs;
  221. for (std::size_t index = 0; index < NUM_SUPPORTED_VERTEX_BINDINGS; ++index) {
  222. if (!flags[Dirty::VertexBuffer0 + index]) {
  223. continue;
  224. }
  225. flags[Dirty::VertexBuffer0 + index] = false;
  226. const auto& vertex_array = regs.vertex_array[index];
  227. if (!vertex_array.IsEnabled()) {
  228. continue;
  229. }
  230. const GPUVAddr start = vertex_array.StartAddress();
  231. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  232. ASSERT(end >= start);
  233. const GLuint gl_index = static_cast<GLuint>(index);
  234. const u64 size = end - start;
  235. if (size == 0) {
  236. glBindVertexBuffer(gl_index, 0, 0, vertex_array.stride);
  237. if (use_unified_memory) {
  238. glBufferAddressRangeNV(GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV, gl_index, 0, 0);
  239. }
  240. continue;
  241. }
  242. const auto info = buffer_cache.UploadMemory(start, size);
  243. if (use_unified_memory) {
  244. glBindVertexBuffer(gl_index, 0, 0, vertex_array.stride);
  245. glBufferAddressRangeNV(GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV, gl_index,
  246. info.address + info.offset, size);
  247. } else {
  248. glBindVertexBuffer(gl_index, info.handle, info.offset, vertex_array.stride);
  249. }
  250. }
  251. }
  252. void RasterizerOpenGL::SetupVertexInstances() {
  253. auto& flags = maxwell3d.dirty.flags;
  254. if (!flags[Dirty::VertexInstances]) {
  255. return;
  256. }
  257. flags[Dirty::VertexInstances] = false;
  258. const auto& regs = maxwell3d.regs;
  259. for (std::size_t index = 0; index < NUM_SUPPORTED_VERTEX_ATTRIBUTES; ++index) {
  260. if (!flags[Dirty::VertexInstance0 + index]) {
  261. continue;
  262. }
  263. flags[Dirty::VertexInstance0 + index] = false;
  264. const auto gl_index = static_cast<GLuint>(index);
  265. const bool instancing_enabled = regs.instanced_arrays.IsInstancingEnabled(gl_index);
  266. const GLuint divisor = instancing_enabled ? regs.vertex_array[index].divisor : 0;
  267. glVertexBindingDivisor(gl_index, divisor);
  268. }
  269. }
  270. GLintptr RasterizerOpenGL::SetupIndexBuffer() {
  271. MICROPROFILE_SCOPE(OpenGL_Index);
  272. const auto& regs = maxwell3d.regs;
  273. const std::size_t size = CalculateIndexBufferSize();
  274. const auto info = buffer_cache.UploadMemory(regs.index_array.IndexStart(), size);
  275. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, info.handle);
  276. return info.offset;
  277. }
  278. void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
  279. MICROPROFILE_SCOPE(OpenGL_Shader);
  280. u32 clip_distances = 0;
  281. for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
  282. const auto& shader_config = maxwell3d.regs.shader_config[index];
  283. const auto program{static_cast<Maxwell::ShaderProgram>(index)};
  284. // Skip stages that are not enabled
  285. if (!maxwell3d.regs.IsShaderConfigEnabled(index)) {
  286. switch (program) {
  287. case Maxwell::ShaderProgram::Geometry:
  288. program_manager.UseGeometryShader(0);
  289. break;
  290. case Maxwell::ShaderProgram::Fragment:
  291. program_manager.UseFragmentShader(0);
  292. break;
  293. default:
  294. break;
  295. }
  296. continue;
  297. }
  298. // Currently this stages are not supported in the OpenGL backend.
  299. // TODO(Blinkhawk): Port tesselation shaders from Vulkan to OpenGL
  300. if (program == Maxwell::ShaderProgram::TesselationControl ||
  301. program == Maxwell::ShaderProgram::TesselationEval) {
  302. continue;
  303. }
  304. Shader* const shader = shader_cache.GetStageProgram(program, async_shaders);
  305. const GLuint program_handle = shader->IsBuilt() ? shader->GetHandle() : 0;
  306. switch (program) {
  307. case Maxwell::ShaderProgram::VertexA:
  308. case Maxwell::ShaderProgram::VertexB:
  309. program_manager.UseVertexShader(program_handle);
  310. break;
  311. case Maxwell::ShaderProgram::Geometry:
  312. program_manager.UseGeometryShader(program_handle);
  313. break;
  314. case Maxwell::ShaderProgram::Fragment:
  315. program_manager.UseFragmentShader(program_handle);
  316. break;
  317. default:
  318. UNIMPLEMENTED_MSG("Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
  319. shader_config.enable.Value(), shader_config.offset);
  320. }
  321. // Stage indices are 0 - 5
  322. const std::size_t stage = index == 0 ? 0 : index - 1;
  323. SetupDrawConstBuffers(stage, shader);
  324. SetupDrawGlobalMemory(stage, shader);
  325. SetupDrawTextures(stage, shader);
  326. SetupDrawImages(stage, shader);
  327. // Workaround for Intel drivers.
  328. // When a clip distance is enabled but not set in the shader it crops parts of the screen
  329. // (sometimes it's half the screen, sometimes three quarters). To avoid this, enable the
  330. // clip distances only when it's written by a shader stage.
  331. clip_distances |= shader->GetEntries().clip_distances;
  332. // When VertexA is enabled, we have dual vertex shaders
  333. if (program == Maxwell::ShaderProgram::VertexA) {
  334. // VertexB was combined with VertexA, so we skip the VertexB iteration
  335. ++index;
  336. }
  337. }
  338. SyncClipEnabled(clip_distances);
  339. maxwell3d.dirty.flags[Dirty::Shaders] = false;
  340. }
  341. std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
  342. const auto& regs = maxwell3d.regs;
  343. std::size_t size = 0;
  344. for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
  345. if (!regs.vertex_array[index].IsEnabled())
  346. continue;
  347. const GPUVAddr start = regs.vertex_array[index].StartAddress();
  348. const GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
  349. size += end - start;
  350. ASSERT(end >= start);
  351. }
  352. return size;
  353. }
  354. std::size_t RasterizerOpenGL::CalculateIndexBufferSize() const {
  355. return static_cast<std::size_t>(maxwell3d.regs.index_array.count) *
  356. static_cast<std::size_t>(maxwell3d.regs.index_array.FormatSizeInBytes());
  357. }
  358. void RasterizerOpenGL::LoadDiskResources(u64 title_id, const std::atomic_bool& stop_loading,
  359. const VideoCore::DiskResourceLoadCallback& callback) {
  360. shader_cache.LoadDiskCache(title_id, stop_loading, callback);
  361. }
  362. void RasterizerOpenGL::ConfigureFramebuffers() {
  363. MICROPROFILE_SCOPE(OpenGL_Framebuffer);
  364. if (!maxwell3d.dirty.flags[VideoCommon::Dirty::RenderTargets]) {
  365. return;
  366. }
  367. maxwell3d.dirty.flags[VideoCommon::Dirty::RenderTargets] = false;
  368. texture_cache.GuardRenderTargets(true);
  369. View depth_surface = texture_cache.GetDepthBufferSurface(true);
  370. const auto& regs = maxwell3d.regs;
  371. UNIMPLEMENTED_IF(regs.rt_separate_frag_data == 0);
  372. // Bind the framebuffer surfaces
  373. FramebufferCacheKey key;
  374. const auto colors_count = static_cast<std::size_t>(regs.rt_control.count);
  375. for (std::size_t index = 0; index < colors_count; ++index) {
  376. View color_surface{texture_cache.GetColorBufferSurface(index, true)};
  377. if (!color_surface) {
  378. continue;
  379. }
  380. // Assume that a surface will be written to if it is used as a framebuffer, even
  381. // if the shader doesn't actually write to it.
  382. texture_cache.MarkColorBufferInUse(index);
  383. key.SetAttachment(index, regs.rt_control.GetMap(index));
  384. key.colors[index] = std::move(color_surface);
  385. }
  386. if (depth_surface) {
  387. // Assume that a surface will be written to if it is used as a framebuffer, even if
  388. // the shader doesn't actually write to it.
  389. texture_cache.MarkDepthBufferInUse();
  390. key.zeta = std::move(depth_surface);
  391. }
  392. texture_cache.GuardRenderTargets(false);
  393. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer_cache.GetFramebuffer(key));
  394. }
  395. void RasterizerOpenGL::ConfigureClearFramebuffer(bool using_color, bool using_depth_stencil) {
  396. const auto& regs = maxwell3d.regs;
  397. texture_cache.GuardRenderTargets(true);
  398. View color_surface;
  399. if (using_color) {
  400. // Determine if we have to preserve the contents.
  401. // First we have to make sure all clear masks are enabled.
  402. bool preserve_contents = !regs.clear_buffers.R || !regs.clear_buffers.G ||
  403. !regs.clear_buffers.B || !regs.clear_buffers.A;
  404. const std::size_t index = regs.clear_buffers.RT;
  405. if (regs.clear_flags.scissor) {
  406. // Then we have to confirm scissor testing clears the whole image.
  407. const auto& scissor = regs.scissor_test[0];
  408. preserve_contents |= scissor.min_x > 0;
  409. preserve_contents |= scissor.min_y > 0;
  410. preserve_contents |= scissor.max_x < regs.rt[index].width;
  411. preserve_contents |= scissor.max_y < regs.rt[index].height;
  412. }
  413. color_surface = texture_cache.GetColorBufferSurface(index, preserve_contents);
  414. texture_cache.MarkColorBufferInUse(index);
  415. }
  416. View depth_surface;
  417. if (using_depth_stencil) {
  418. bool preserve_contents = false;
  419. if (regs.clear_flags.scissor) {
  420. // For depth stencil clears we only have to confirm scissor test covers the whole image.
  421. const auto& scissor = regs.scissor_test[0];
  422. preserve_contents |= scissor.min_x > 0;
  423. preserve_contents |= scissor.min_y > 0;
  424. preserve_contents |= scissor.max_x < regs.zeta_width;
  425. preserve_contents |= scissor.max_y < regs.zeta_height;
  426. }
  427. depth_surface = texture_cache.GetDepthBufferSurface(preserve_contents);
  428. texture_cache.MarkDepthBufferInUse();
  429. }
  430. texture_cache.GuardRenderTargets(false);
  431. FramebufferCacheKey key;
  432. key.colors[0] = std::move(color_surface);
  433. key.zeta = std::move(depth_surface);
  434. state_tracker.NotifyFramebuffer();
  435. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer_cache.GetFramebuffer(key));
  436. }
  437. void RasterizerOpenGL::Clear() {
  438. if (!maxwell3d.ShouldExecute()) {
  439. return;
  440. }
  441. const auto& regs = maxwell3d.regs;
  442. bool use_color{};
  443. bool use_depth{};
  444. bool use_stencil{};
  445. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  446. regs.clear_buffers.A) {
  447. use_color = true;
  448. state_tracker.NotifyColorMask0();
  449. glColorMaski(0, regs.clear_buffers.R != 0, regs.clear_buffers.G != 0,
  450. regs.clear_buffers.B != 0, regs.clear_buffers.A != 0);
  451. // TODO(Rodrigo): Determine if clamping is used on clears
  452. SyncFragmentColorClampState();
  453. SyncFramebufferSRGB();
  454. }
  455. if (regs.clear_buffers.Z) {
  456. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  457. use_depth = true;
  458. state_tracker.NotifyDepthMask();
  459. glDepthMask(GL_TRUE);
  460. }
  461. if (regs.clear_buffers.S) {
  462. ASSERT_MSG(regs.zeta_enable, "Tried to clear stencil but buffer is not enabled!");
  463. use_stencil = true;
  464. }
  465. if (!use_color && !use_depth && !use_stencil) {
  466. // No color surface nor depth/stencil surface are enabled
  467. return;
  468. }
  469. SyncRasterizeEnable();
  470. SyncStencilTestState();
  471. if (regs.clear_flags.scissor) {
  472. SyncScissorTest();
  473. } else {
  474. state_tracker.NotifyScissor0();
  475. glDisablei(GL_SCISSOR_TEST, 0);
  476. }
  477. UNIMPLEMENTED_IF(regs.clear_flags.viewport);
  478. ConfigureClearFramebuffer(use_color, use_depth || use_stencil);
  479. if (use_color) {
  480. glClearBufferfv(GL_COLOR, 0, regs.clear_color);
  481. }
  482. if (use_depth && use_stencil) {
  483. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  484. } else if (use_depth) {
  485. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  486. } else if (use_stencil) {
  487. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  488. }
  489. ++num_queued_commands;
  490. }
  491. void RasterizerOpenGL::Draw(bool is_indexed, bool is_instanced) {
  492. MICROPROFILE_SCOPE(OpenGL_Drawing);
  493. query_cache.UpdateCounters();
  494. SyncViewport();
  495. SyncRasterizeEnable();
  496. SyncPolygonModes();
  497. SyncColorMask();
  498. SyncFragmentColorClampState();
  499. SyncMultiSampleState();
  500. SyncDepthTestState();
  501. SyncDepthClamp();
  502. SyncStencilTestState();
  503. SyncBlendState();
  504. SyncLogicOpState();
  505. SyncCullMode();
  506. SyncPrimitiveRestart();
  507. SyncScissorTest();
  508. SyncPointState();
  509. SyncLineState();
  510. SyncPolygonOffset();
  511. SyncAlphaTest();
  512. SyncFramebufferSRGB();
  513. buffer_cache.Acquire();
  514. current_cbuf = 0;
  515. std::size_t buffer_size = CalculateVertexArraysSize();
  516. // Add space for index buffer
  517. if (is_indexed) {
  518. buffer_size = Common::AlignUp(buffer_size, 4) + CalculateIndexBufferSize();
  519. }
  520. // Uniform space for the 5 shader stages
  521. buffer_size =
  522. Common::AlignUp<std::size_t>(buffer_size, 4) +
  523. (sizeof(MaxwellUniformData) + device.GetUniformBufferAlignment()) * Maxwell::MaxShaderStage;
  524. // Add space for at least 18 constant buffers
  525. buffer_size += Maxwell::MaxConstBuffers *
  526. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  527. // Prepare the vertex array.
  528. const bool invalidated = buffer_cache.Map(buffer_size);
  529. if (invalidated) {
  530. // When the stream buffer has been invalidated, we have to consider vertex buffers as dirty
  531. auto& dirty = maxwell3d.dirty.flags;
  532. dirty[Dirty::VertexBuffers] = true;
  533. for (int index = Dirty::VertexBuffer0; index <= Dirty::VertexBuffer31; ++index) {
  534. dirty[index] = true;
  535. }
  536. }
  537. // Prepare vertex array format.
  538. SetupVertexFormat();
  539. // Upload vertex and index data.
  540. SetupVertexBuffer();
  541. SetupVertexInstances();
  542. GLintptr index_buffer_offset = 0;
  543. if (is_indexed) {
  544. index_buffer_offset = SetupIndexBuffer();
  545. }
  546. // Setup emulation uniform buffer.
  547. if (!device.UseAssemblyShaders()) {
  548. MaxwellUniformData ubo;
  549. ubo.SetFromRegs(maxwell3d);
  550. const auto info =
  551. buffer_cache.UploadHostMemory(&ubo, sizeof(ubo), device.GetUniformBufferAlignment());
  552. glBindBufferRange(GL_UNIFORM_BUFFER, EmulationUniformBlockBinding, info.handle, info.offset,
  553. static_cast<GLsizeiptr>(sizeof(ubo)));
  554. }
  555. // Setup shaders and their used resources.
  556. texture_cache.GuardSamplers(true);
  557. const GLenum primitive_mode = MaxwellToGL::PrimitiveTopology(maxwell3d.regs.draw.topology);
  558. SetupShaders(primitive_mode);
  559. texture_cache.GuardSamplers(false);
  560. ConfigureFramebuffers();
  561. // Signal the buffer cache that we are not going to upload more things.
  562. buffer_cache.Unmap();
  563. program_manager.BindGraphicsPipeline();
  564. if (texture_cache.TextureBarrier()) {
  565. glTextureBarrier();
  566. }
  567. BeginTransformFeedback(primitive_mode);
  568. const GLuint base_instance = static_cast<GLuint>(maxwell3d.regs.vb_base_instance);
  569. const GLsizei num_instances =
  570. static_cast<GLsizei>(is_instanced ? maxwell3d.mme_draw.instance_count : 1);
  571. if (is_indexed) {
  572. const GLint base_vertex = static_cast<GLint>(maxwell3d.regs.vb_element_base);
  573. const GLsizei num_vertices = static_cast<GLsizei>(maxwell3d.regs.index_array.count);
  574. const GLvoid* offset = reinterpret_cast<const GLvoid*>(index_buffer_offset);
  575. const GLenum format = MaxwellToGL::IndexFormat(maxwell3d.regs.index_array.format);
  576. if (num_instances == 1 && base_instance == 0 && base_vertex == 0) {
  577. glDrawElements(primitive_mode, num_vertices, format, offset);
  578. } else if (num_instances == 1 && base_instance == 0) {
  579. glDrawElementsBaseVertex(primitive_mode, num_vertices, format, offset, base_vertex);
  580. } else if (base_vertex == 0 && base_instance == 0) {
  581. glDrawElementsInstanced(primitive_mode, num_vertices, format, offset, num_instances);
  582. } else if (base_vertex == 0) {
  583. glDrawElementsInstancedBaseInstance(primitive_mode, num_vertices, format, offset,
  584. num_instances, base_instance);
  585. } else if (base_instance == 0) {
  586. glDrawElementsInstancedBaseVertex(primitive_mode, num_vertices, format, offset,
  587. num_instances, base_vertex);
  588. } else {
  589. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, num_vertices, format,
  590. offset, num_instances, base_vertex,
  591. base_instance);
  592. }
  593. } else {
  594. const GLint base_vertex = static_cast<GLint>(maxwell3d.regs.vertex_buffer.first);
  595. const GLsizei num_vertices = static_cast<GLsizei>(maxwell3d.regs.vertex_buffer.count);
  596. if (num_instances == 1 && base_instance == 0) {
  597. glDrawArrays(primitive_mode, base_vertex, num_vertices);
  598. } else if (base_instance == 0) {
  599. glDrawArraysInstanced(primitive_mode, base_vertex, num_vertices, num_instances);
  600. } else {
  601. glDrawArraysInstancedBaseInstance(primitive_mode, base_vertex, num_vertices,
  602. num_instances, base_instance);
  603. }
  604. }
  605. EndTransformFeedback();
  606. ++num_queued_commands;
  607. gpu.TickWork();
  608. }
  609. void RasterizerOpenGL::DispatchCompute(GPUVAddr code_addr) {
  610. buffer_cache.Acquire();
  611. current_cbuf = 0;
  612. auto kernel = shader_cache.GetComputeKernel(code_addr);
  613. program_manager.BindCompute(kernel->GetHandle());
  614. SetupComputeTextures(kernel);
  615. SetupComputeImages(kernel);
  616. const std::size_t buffer_size =
  617. Tegra::Engines::KeplerCompute::NumConstBuffers *
  618. (Maxwell::MaxConstBufferSize + device.GetUniformBufferAlignment());
  619. buffer_cache.Map(buffer_size);
  620. SetupComputeConstBuffers(kernel);
  621. SetupComputeGlobalMemory(kernel);
  622. buffer_cache.Unmap();
  623. const auto& launch_desc = kepler_compute.launch_description;
  624. program_manager.BindCompute(kernel->GetHandle());
  625. glDispatchCompute(launch_desc.grid_dim_x, launch_desc.grid_dim_y, launch_desc.grid_dim_z);
  626. ++num_queued_commands;
  627. }
  628. void RasterizerOpenGL::ResetCounter(VideoCore::QueryType type) {
  629. query_cache.ResetCounter(type);
  630. }
  631. void RasterizerOpenGL::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  632. std::optional<u64> timestamp) {
  633. query_cache.Query(gpu_addr, type, timestamp);
  634. }
  635. void RasterizerOpenGL::FlushAll() {}
  636. void RasterizerOpenGL::FlushRegion(VAddr addr, u64 size) {
  637. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  638. if (addr == 0 || size == 0) {
  639. return;
  640. }
  641. texture_cache.FlushRegion(addr, size);
  642. buffer_cache.FlushRegion(addr, size);
  643. query_cache.FlushRegion(addr, size);
  644. }
  645. bool RasterizerOpenGL::MustFlushRegion(VAddr addr, u64 size) {
  646. if (!Settings::IsGPULevelHigh()) {
  647. return buffer_cache.MustFlushRegion(addr, size);
  648. }
  649. return texture_cache.MustFlushRegion(addr, size) || buffer_cache.MustFlushRegion(addr, size);
  650. }
  651. void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size) {
  652. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  653. if (addr == 0 || size == 0) {
  654. return;
  655. }
  656. texture_cache.InvalidateRegion(addr, size);
  657. shader_cache.InvalidateRegion(addr, size);
  658. buffer_cache.InvalidateRegion(addr, size);
  659. query_cache.InvalidateRegion(addr, size);
  660. }
  661. void RasterizerOpenGL::OnCPUWrite(VAddr addr, u64 size) {
  662. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  663. if (addr == 0 || size == 0) {
  664. return;
  665. }
  666. texture_cache.OnCPUWrite(addr, size);
  667. shader_cache.OnCPUWrite(addr, size);
  668. buffer_cache.OnCPUWrite(addr, size);
  669. }
  670. void RasterizerOpenGL::SyncGuestHost() {
  671. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  672. texture_cache.SyncGuestHost();
  673. buffer_cache.SyncGuestHost();
  674. shader_cache.SyncGuestHost();
  675. }
  676. void RasterizerOpenGL::SignalSemaphore(GPUVAddr addr, u32 value) {
  677. if (!gpu.IsAsync()) {
  678. gpu_memory.Write<u32>(addr, value);
  679. return;
  680. }
  681. fence_manager.SignalSemaphore(addr, value);
  682. }
  683. void RasterizerOpenGL::SignalSyncPoint(u32 value) {
  684. if (!gpu.IsAsync()) {
  685. gpu.IncrementSyncPoint(value);
  686. return;
  687. }
  688. fence_manager.SignalSyncPoint(value);
  689. }
  690. void RasterizerOpenGL::ReleaseFences() {
  691. if (!gpu.IsAsync()) {
  692. return;
  693. }
  694. fence_manager.WaitPendingFences();
  695. }
  696. void RasterizerOpenGL::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  697. if (Settings::IsGPULevelExtreme()) {
  698. FlushRegion(addr, size);
  699. }
  700. InvalidateRegion(addr, size);
  701. }
  702. void RasterizerOpenGL::WaitForIdle() {
  703. // Place a barrier on everything that is not framebuffer related.
  704. // This is related to another flag that is not currently implemented.
  705. glMemoryBarrier(GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT | GL_ELEMENT_ARRAY_BARRIER_BIT |
  706. GL_UNIFORM_BARRIER_BIT | GL_TEXTURE_FETCH_BARRIER_BIT |
  707. GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL_COMMAND_BARRIER_BIT |
  708. GL_PIXEL_BUFFER_BARRIER_BIT | GL_TEXTURE_UPDATE_BARRIER_BIT |
  709. GL_BUFFER_UPDATE_BARRIER_BIT | GL_TRANSFORM_FEEDBACK_BARRIER_BIT |
  710. GL_SHADER_STORAGE_BARRIER_BIT | GL_QUERY_BUFFER_BARRIER_BIT);
  711. }
  712. void RasterizerOpenGL::FlushCommands() {
  713. // Only flush when we have commands queued to OpenGL.
  714. if (num_queued_commands == 0) {
  715. return;
  716. }
  717. num_queued_commands = 0;
  718. glFlush();
  719. }
  720. void RasterizerOpenGL::TickFrame() {
  721. // Ticking a frame means that buffers will be swapped, calling glFlush implicitly.
  722. num_queued_commands = 0;
  723. buffer_cache.TickFrame();
  724. }
  725. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Regs::Surface& src,
  726. const Tegra::Engines::Fermi2D::Regs::Surface& dst,
  727. const Tegra::Engines::Fermi2D::Config& copy_config) {
  728. MICROPROFILE_SCOPE(OpenGL_Blits);
  729. texture_cache.DoFermiCopy(src, dst, copy_config);
  730. return true;
  731. }
  732. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  733. VAddr framebuffer_addr, u32 pixel_stride) {
  734. if (!framebuffer_addr) {
  735. return {};
  736. }
  737. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  738. const auto surface{texture_cache.TryFindFramebufferSurface(framebuffer_addr)};
  739. if (!surface) {
  740. return {};
  741. }
  742. // Verify that the cached surface is the same size and format as the requested framebuffer
  743. const auto& params{surface->GetSurfaceParams()};
  744. const auto& pixel_format{
  745. VideoCore::Surface::PixelFormatFromGPUPixelFormat(config.pixel_format)};
  746. ASSERT_MSG(params.width == config.width, "Framebuffer width is different");
  747. ASSERT_MSG(params.height == config.height, "Framebuffer height is different");
  748. if (params.pixel_format != pixel_format) {
  749. LOG_DEBUG(Render_OpenGL, "Framebuffer pixel_format is different");
  750. }
  751. screen_info.display_texture = surface->GetTexture();
  752. screen_info.display_srgb = surface->GetSurfaceParams().srgb_conversion;
  753. return true;
  754. }
  755. void RasterizerOpenGL::SetupDrawConstBuffers(std::size_t stage_index, Shader* shader) {
  756. static constexpr std::array PARAMETER_LUT{
  757. GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV, GL_TESS_CONTROL_PROGRAM_PARAMETER_BUFFER_NV,
  758. GL_TESS_EVALUATION_PROGRAM_PARAMETER_BUFFER_NV, GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV,
  759. GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV,
  760. };
  761. MICROPROFILE_SCOPE(OpenGL_UBO);
  762. const auto& stages = maxwell3d.state.shader_stages;
  763. const auto& shader_stage = stages[stage_index];
  764. const auto& entries = shader->GetEntries();
  765. const bool use_unified = entries.use_unified_uniforms;
  766. const std::size_t base_unified_offset = stage_index * NUM_CONST_BUFFERS_BYTES_PER_STAGE;
  767. const auto base_bindings = device.GetBaseBindings(stage_index);
  768. u32 binding = device.UseAssemblyShaders() ? 0 : base_bindings.uniform_buffer;
  769. for (const auto& entry : entries.const_buffers) {
  770. const u32 index = entry.GetIndex();
  771. const auto& buffer = shader_stage.const_buffers[index];
  772. SetupConstBuffer(PARAMETER_LUT[stage_index], binding, buffer, entry, use_unified,
  773. base_unified_offset + index * Maxwell::MaxConstBufferSize);
  774. ++binding;
  775. }
  776. if (use_unified) {
  777. const u32 index = static_cast<u32>(base_bindings.shader_storage_buffer +
  778. entries.global_memory_entries.size());
  779. glBindBufferRange(GL_SHADER_STORAGE_BUFFER, index, unified_uniform_buffer.handle,
  780. base_unified_offset, NUM_CONST_BUFFERS_BYTES_PER_STAGE);
  781. }
  782. }
  783. void RasterizerOpenGL::SetupComputeConstBuffers(Shader* kernel) {
  784. MICROPROFILE_SCOPE(OpenGL_UBO);
  785. const auto& launch_desc = kepler_compute.launch_description;
  786. const auto& entries = kernel->GetEntries();
  787. const bool use_unified = entries.use_unified_uniforms;
  788. u32 binding = 0;
  789. for (const auto& entry : entries.const_buffers) {
  790. const auto& config = launch_desc.const_buffer_config[entry.GetIndex()];
  791. const std::bitset<8> mask = launch_desc.const_buffer_enable_mask.Value();
  792. Tegra::Engines::ConstBufferInfo buffer;
  793. buffer.address = config.Address();
  794. buffer.size = config.size;
  795. buffer.enabled = mask[entry.GetIndex()];
  796. SetupConstBuffer(GL_COMPUTE_PROGRAM_PARAMETER_BUFFER_NV, binding, buffer, entry,
  797. use_unified, entry.GetIndex() * Maxwell::MaxConstBufferSize);
  798. ++binding;
  799. }
  800. if (use_unified) {
  801. const GLuint index = static_cast<GLuint>(entries.global_memory_entries.size());
  802. glBindBufferRange(GL_SHADER_STORAGE_BUFFER, index, unified_uniform_buffer.handle, 0,
  803. NUM_CONST_BUFFERS_BYTES_PER_STAGE);
  804. }
  805. }
  806. void RasterizerOpenGL::SetupConstBuffer(GLenum stage, u32 binding,
  807. const Tegra::Engines::ConstBufferInfo& buffer,
  808. const ConstBufferEntry& entry, bool use_unified,
  809. std::size_t unified_offset) {
  810. if (!buffer.enabled) {
  811. // Set values to zero to unbind buffers
  812. if (device.UseAssemblyShaders()) {
  813. glBindBufferRangeNV(stage, entry.GetIndex(), 0, 0, 0);
  814. } else {
  815. glBindBufferRange(GL_UNIFORM_BUFFER, binding, 0, 0, sizeof(float));
  816. }
  817. return;
  818. }
  819. // Align the actual size so it ends up being a multiple of vec4 to meet the OpenGL std140
  820. // UBO alignment requirements.
  821. const std::size_t size = Common::AlignUp(GetConstBufferSize(buffer, entry), sizeof(GLvec4));
  822. const bool fast_upload = !use_unified && device.HasFastBufferSubData();
  823. const std::size_t alignment = use_unified ? 4 : device.GetUniformBufferAlignment();
  824. const GPUVAddr gpu_addr = buffer.address;
  825. auto info = buffer_cache.UploadMemory(gpu_addr, size, alignment, false, fast_upload);
  826. if (device.UseAssemblyShaders()) {
  827. UNIMPLEMENTED_IF(use_unified);
  828. if (info.offset != 0) {
  829. const GLuint staging_cbuf = staging_cbufs[current_cbuf++];
  830. glCopyNamedBufferSubData(info.handle, staging_cbuf, info.offset, 0, size);
  831. info.handle = staging_cbuf;
  832. info.offset = 0;
  833. }
  834. glBindBufferRangeNV(stage, binding, info.handle, info.offset, size);
  835. return;
  836. }
  837. if (use_unified) {
  838. glCopyNamedBufferSubData(info.handle, unified_uniform_buffer.handle, info.offset,
  839. unified_offset, size);
  840. } else {
  841. glBindBufferRange(GL_UNIFORM_BUFFER, binding, info.handle, info.offset, size);
  842. }
  843. }
  844. void RasterizerOpenGL::SetupDrawGlobalMemory(std::size_t stage_index, Shader* shader) {
  845. static constexpr std::array TARGET_LUT = {
  846. GL_VERTEX_PROGRAM_NV, GL_TESS_CONTROL_PROGRAM_NV, GL_TESS_EVALUATION_PROGRAM_NV,
  847. GL_GEOMETRY_PROGRAM_NV, GL_FRAGMENT_PROGRAM_NV,
  848. };
  849. const auto& cbufs{maxwell3d.state.shader_stages[stage_index]};
  850. const auto& entries{shader->GetEntries().global_memory_entries};
  851. std::array<BindlessSSBO, 32> ssbos;
  852. ASSERT(entries.size() < ssbos.size());
  853. const bool assembly_shaders = device.UseAssemblyShaders();
  854. u32 binding = assembly_shaders ? 0 : device.GetBaseBindings(stage_index).shader_storage_buffer;
  855. for (const auto& entry : entries) {
  856. const GPUVAddr addr{cbufs.const_buffers[entry.cbuf_index].address + entry.cbuf_offset};
  857. const GPUVAddr gpu_addr{gpu_memory.Read<u64>(addr)};
  858. const u32 size{gpu_memory.Read<u32>(addr + 8)};
  859. SetupGlobalMemory(binding, entry, gpu_addr, size, &ssbos[binding]);
  860. ++binding;
  861. }
  862. if (assembly_shaders) {
  863. UpdateBindlessSSBOs(TARGET_LUT[stage_index], ssbos.data(), entries.size());
  864. }
  865. }
  866. void RasterizerOpenGL::SetupComputeGlobalMemory(Shader* kernel) {
  867. const auto& cbufs{kepler_compute.launch_description.const_buffer_config};
  868. const auto& entries{kernel->GetEntries().global_memory_entries};
  869. std::array<BindlessSSBO, 32> ssbos;
  870. ASSERT(entries.size() < ssbos.size());
  871. u32 binding = 0;
  872. for (const auto& entry : entries) {
  873. const GPUVAddr addr{cbufs[entry.cbuf_index].Address() + entry.cbuf_offset};
  874. const GPUVAddr gpu_addr{gpu_memory.Read<u64>(addr)};
  875. const u32 size{gpu_memory.Read<u32>(addr + 8)};
  876. SetupGlobalMemory(binding, entry, gpu_addr, size, &ssbos[binding]);
  877. ++binding;
  878. }
  879. if (device.UseAssemblyShaders()) {
  880. UpdateBindlessSSBOs(GL_COMPUTE_PROGRAM_NV, ssbos.data(), ssbos.size());
  881. }
  882. }
  883. void RasterizerOpenGL::SetupGlobalMemory(u32 binding, const GlobalMemoryEntry& entry,
  884. GPUVAddr gpu_addr, size_t size, BindlessSSBO* ssbo) {
  885. const size_t alignment{device.GetShaderStorageBufferAlignment()};
  886. const auto info = buffer_cache.UploadMemory(gpu_addr, size, alignment, entry.is_written);
  887. if (device.UseAssemblyShaders()) {
  888. *ssbo = BindlessSSBO{
  889. .address = static_cast<GLuint64EXT>(info.address + info.offset),
  890. .length = static_cast<GLsizei>(size),
  891. .padding = 0,
  892. };
  893. } else {
  894. glBindBufferRange(GL_SHADER_STORAGE_BUFFER, binding, info.handle, info.offset,
  895. static_cast<GLsizeiptr>(size));
  896. }
  897. }
  898. void RasterizerOpenGL::SetupDrawTextures(std::size_t stage_index, Shader* shader) {
  899. MICROPROFILE_SCOPE(OpenGL_Texture);
  900. u32 binding = device.GetBaseBindings(stage_index).sampler;
  901. for (const auto& entry : shader->GetEntries().samplers) {
  902. const auto shader_type = static_cast<ShaderType>(stage_index);
  903. for (std::size_t i = 0; i < entry.size; ++i) {
  904. const auto texture = GetTextureInfo(maxwell3d, entry, shader_type, i);
  905. SetupTexture(binding++, texture, entry);
  906. }
  907. }
  908. }
  909. void RasterizerOpenGL::SetupComputeTextures(Shader* kernel) {
  910. MICROPROFILE_SCOPE(OpenGL_Texture);
  911. u32 binding = 0;
  912. for (const auto& entry : kernel->GetEntries().samplers) {
  913. for (std::size_t i = 0; i < entry.size; ++i) {
  914. const auto texture = GetTextureInfo(kepler_compute, entry, ShaderType::Compute, i);
  915. SetupTexture(binding++, texture, entry);
  916. }
  917. }
  918. }
  919. void RasterizerOpenGL::SetupTexture(u32 binding, const Tegra::Texture::FullTextureInfo& texture,
  920. const SamplerEntry& entry) {
  921. const auto view = texture_cache.GetTextureSurface(texture.tic, entry);
  922. if (!view) {
  923. // Can occur when texture addr is null or its memory is unmapped/invalid
  924. glBindSampler(binding, 0);
  925. glBindTextureUnit(binding, 0);
  926. return;
  927. }
  928. const GLuint handle = view->GetTexture(texture.tic.x_source, texture.tic.y_source,
  929. texture.tic.z_source, texture.tic.w_source);
  930. glBindTextureUnit(binding, handle);
  931. if (!view->GetSurfaceParams().IsBuffer()) {
  932. glBindSampler(binding, sampler_cache.GetSampler(texture.tsc));
  933. }
  934. }
  935. void RasterizerOpenGL::SetupDrawImages(std::size_t stage_index, Shader* shader) {
  936. u32 binding = device.GetBaseBindings(stage_index).image;
  937. for (const auto& entry : shader->GetEntries().images) {
  938. const auto shader_type = static_cast<ShaderType>(stage_index);
  939. const auto tic = GetTextureInfo(maxwell3d, entry, shader_type).tic;
  940. SetupImage(binding++, tic, entry);
  941. }
  942. }
  943. void RasterizerOpenGL::SetupComputeImages(Shader* shader) {
  944. u32 binding = 0;
  945. for (const auto& entry : shader->GetEntries().images) {
  946. const auto tic = GetTextureInfo(kepler_compute, entry, ShaderType::Compute).tic;
  947. SetupImage(binding++, tic, entry);
  948. }
  949. }
  950. void RasterizerOpenGL::SetupImage(u32 binding, const Tegra::Texture::TICEntry& tic,
  951. const ImageEntry& entry) {
  952. const auto view = texture_cache.GetImageSurface(tic, entry);
  953. if (!view) {
  954. glBindImageTexture(binding, 0, 0, GL_FALSE, 0, GL_READ_ONLY, GL_R8);
  955. return;
  956. }
  957. if (entry.is_written) {
  958. view->MarkAsModified(texture_cache.Tick());
  959. }
  960. const GLuint handle = view->GetTexture(tic.x_source, tic.y_source, tic.z_source, tic.w_source);
  961. glBindImageTexture(binding, handle, 0, GL_TRUE, 0, GL_READ_WRITE, view->GetFormat());
  962. }
  963. void RasterizerOpenGL::SyncViewport() {
  964. auto& flags = maxwell3d.dirty.flags;
  965. const auto& regs = maxwell3d.regs;
  966. const bool dirty_viewport = flags[Dirty::Viewports];
  967. const bool dirty_clip_control = flags[Dirty::ClipControl];
  968. if (dirty_clip_control || flags[Dirty::FrontFace]) {
  969. flags[Dirty::FrontFace] = false;
  970. GLenum mode = MaxwellToGL::FrontFace(regs.front_face);
  971. if (regs.screen_y_control.triangle_rast_flip != 0 &&
  972. regs.viewport_transform[0].scale_y < 0.0f) {
  973. switch (mode) {
  974. case GL_CW:
  975. mode = GL_CCW;
  976. break;
  977. case GL_CCW:
  978. mode = GL_CW;
  979. break;
  980. }
  981. }
  982. glFrontFace(mode);
  983. }
  984. if (dirty_viewport || flags[Dirty::ClipControl]) {
  985. flags[Dirty::ClipControl] = false;
  986. bool flip_y = false;
  987. if (regs.viewport_transform[0].scale_y < 0.0) {
  988. flip_y = !flip_y;
  989. }
  990. if (regs.screen_y_control.y_negate != 0) {
  991. flip_y = !flip_y;
  992. }
  993. glClipControl(flip_y ? GL_UPPER_LEFT : GL_LOWER_LEFT,
  994. regs.depth_mode == Maxwell::DepthMode::ZeroToOne ? GL_ZERO_TO_ONE
  995. : GL_NEGATIVE_ONE_TO_ONE);
  996. }
  997. if (dirty_viewport) {
  998. flags[Dirty::Viewports] = false;
  999. const bool force = flags[Dirty::ViewportTransform];
  1000. flags[Dirty::ViewportTransform] = false;
  1001. for (std::size_t i = 0; i < Maxwell::NumViewports; ++i) {
  1002. if (!force && !flags[Dirty::Viewport0 + i]) {
  1003. continue;
  1004. }
  1005. flags[Dirty::Viewport0 + i] = false;
  1006. const auto& src = regs.viewport_transform[i];
  1007. const Common::Rectangle<f32> rect{src.GetRect()};
  1008. glViewportIndexedf(static_cast<GLuint>(i), rect.left, rect.bottom, rect.GetWidth(),
  1009. rect.GetHeight());
  1010. const GLdouble reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne;
  1011. const GLdouble near_depth = src.translate_z - src.scale_z * reduce_z;
  1012. const GLdouble far_depth = src.translate_z + src.scale_z;
  1013. glDepthRangeIndexed(static_cast<GLuint>(i), near_depth, far_depth);
  1014. if (!GLAD_GL_NV_viewport_swizzle) {
  1015. continue;
  1016. }
  1017. glViewportSwizzleNV(static_cast<GLuint>(i), MaxwellToGL::ViewportSwizzle(src.swizzle.x),
  1018. MaxwellToGL::ViewportSwizzle(src.swizzle.y),
  1019. MaxwellToGL::ViewportSwizzle(src.swizzle.z),
  1020. MaxwellToGL::ViewportSwizzle(src.swizzle.w));
  1021. }
  1022. }
  1023. }
  1024. void RasterizerOpenGL::SyncDepthClamp() {
  1025. auto& flags = maxwell3d.dirty.flags;
  1026. if (!flags[Dirty::DepthClampEnabled]) {
  1027. return;
  1028. }
  1029. flags[Dirty::DepthClampEnabled] = false;
  1030. oglEnable(GL_DEPTH_CLAMP, maxwell3d.regs.view_volume_clip_control.depth_clamp_disabled == 0);
  1031. }
  1032. void RasterizerOpenGL::SyncClipEnabled(u32 clip_mask) {
  1033. auto& flags = maxwell3d.dirty.flags;
  1034. if (!flags[Dirty::ClipDistances] && !flags[Dirty::Shaders]) {
  1035. return;
  1036. }
  1037. flags[Dirty::ClipDistances] = false;
  1038. clip_mask &= maxwell3d.regs.clip_distance_enabled;
  1039. if (clip_mask == last_clip_distance_mask) {
  1040. return;
  1041. }
  1042. last_clip_distance_mask = clip_mask;
  1043. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  1044. oglEnable(static_cast<GLenum>(GL_CLIP_DISTANCE0 + i), (clip_mask >> i) & 1);
  1045. }
  1046. }
  1047. void RasterizerOpenGL::SyncClipCoef() {
  1048. UNIMPLEMENTED();
  1049. }
  1050. void RasterizerOpenGL::SyncCullMode() {
  1051. auto& flags = maxwell3d.dirty.flags;
  1052. const auto& regs = maxwell3d.regs;
  1053. if (flags[Dirty::CullTest]) {
  1054. flags[Dirty::CullTest] = false;
  1055. if (regs.cull_test_enabled) {
  1056. glEnable(GL_CULL_FACE);
  1057. glCullFace(MaxwellToGL::CullFace(regs.cull_face));
  1058. } else {
  1059. glDisable(GL_CULL_FACE);
  1060. }
  1061. }
  1062. }
  1063. void RasterizerOpenGL::SyncPrimitiveRestart() {
  1064. auto& flags = maxwell3d.dirty.flags;
  1065. if (!flags[Dirty::PrimitiveRestart]) {
  1066. return;
  1067. }
  1068. flags[Dirty::PrimitiveRestart] = false;
  1069. if (maxwell3d.regs.primitive_restart.enabled) {
  1070. glEnable(GL_PRIMITIVE_RESTART);
  1071. glPrimitiveRestartIndex(maxwell3d.regs.primitive_restart.index);
  1072. } else {
  1073. glDisable(GL_PRIMITIVE_RESTART);
  1074. }
  1075. }
  1076. void RasterizerOpenGL::SyncDepthTestState() {
  1077. auto& flags = maxwell3d.dirty.flags;
  1078. const auto& regs = maxwell3d.regs;
  1079. if (flags[Dirty::DepthMask]) {
  1080. flags[Dirty::DepthMask] = false;
  1081. glDepthMask(regs.depth_write_enabled ? GL_TRUE : GL_FALSE);
  1082. }
  1083. if (flags[Dirty::DepthTest]) {
  1084. flags[Dirty::DepthTest] = false;
  1085. if (regs.depth_test_enable) {
  1086. glEnable(GL_DEPTH_TEST);
  1087. glDepthFunc(MaxwellToGL::ComparisonOp(regs.depth_test_func));
  1088. } else {
  1089. glDisable(GL_DEPTH_TEST);
  1090. }
  1091. }
  1092. }
  1093. void RasterizerOpenGL::SyncStencilTestState() {
  1094. auto& flags = maxwell3d.dirty.flags;
  1095. if (!flags[Dirty::StencilTest]) {
  1096. return;
  1097. }
  1098. flags[Dirty::StencilTest] = false;
  1099. const auto& regs = maxwell3d.regs;
  1100. oglEnable(GL_STENCIL_TEST, regs.stencil_enable);
  1101. glStencilFuncSeparate(GL_FRONT, MaxwellToGL::ComparisonOp(regs.stencil_front_func_func),
  1102. regs.stencil_front_func_ref, regs.stencil_front_func_mask);
  1103. glStencilOpSeparate(GL_FRONT, MaxwellToGL::StencilOp(regs.stencil_front_op_fail),
  1104. MaxwellToGL::StencilOp(regs.stencil_front_op_zfail),
  1105. MaxwellToGL::StencilOp(regs.stencil_front_op_zpass));
  1106. glStencilMaskSeparate(GL_FRONT, regs.stencil_front_mask);
  1107. if (regs.stencil_two_side_enable) {
  1108. glStencilFuncSeparate(GL_BACK, MaxwellToGL::ComparisonOp(regs.stencil_back_func_func),
  1109. regs.stencil_back_func_ref, regs.stencil_back_func_mask);
  1110. glStencilOpSeparate(GL_BACK, MaxwellToGL::StencilOp(regs.stencil_back_op_fail),
  1111. MaxwellToGL::StencilOp(regs.stencil_back_op_zfail),
  1112. MaxwellToGL::StencilOp(regs.stencil_back_op_zpass));
  1113. glStencilMaskSeparate(GL_BACK, regs.stencil_back_mask);
  1114. } else {
  1115. glStencilFuncSeparate(GL_BACK, GL_ALWAYS, 0, 0xFFFFFFFF);
  1116. glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP);
  1117. glStencilMaskSeparate(GL_BACK, 0xFFFFFFFF);
  1118. }
  1119. }
  1120. void RasterizerOpenGL::SyncRasterizeEnable() {
  1121. auto& flags = maxwell3d.dirty.flags;
  1122. if (!flags[Dirty::RasterizeEnable]) {
  1123. return;
  1124. }
  1125. flags[Dirty::RasterizeEnable] = false;
  1126. oglEnable(GL_RASTERIZER_DISCARD, maxwell3d.regs.rasterize_enable == 0);
  1127. }
  1128. void RasterizerOpenGL::SyncPolygonModes() {
  1129. auto& flags = maxwell3d.dirty.flags;
  1130. if (!flags[Dirty::PolygonModes]) {
  1131. return;
  1132. }
  1133. flags[Dirty::PolygonModes] = false;
  1134. const auto& regs = maxwell3d.regs;
  1135. if (regs.fill_rectangle) {
  1136. if (!GLAD_GL_NV_fill_rectangle) {
  1137. LOG_ERROR(Render_OpenGL, "GL_NV_fill_rectangle used and not supported");
  1138. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  1139. return;
  1140. }
  1141. flags[Dirty::PolygonModeFront] = true;
  1142. flags[Dirty::PolygonModeBack] = true;
  1143. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL_RECTANGLE_NV);
  1144. return;
  1145. }
  1146. if (regs.polygon_mode_front == regs.polygon_mode_back) {
  1147. flags[Dirty::PolygonModeFront] = false;
  1148. flags[Dirty::PolygonModeBack] = false;
  1149. glPolygonMode(GL_FRONT_AND_BACK, MaxwellToGL::PolygonMode(regs.polygon_mode_front));
  1150. return;
  1151. }
  1152. if (flags[Dirty::PolygonModeFront]) {
  1153. flags[Dirty::PolygonModeFront] = false;
  1154. glPolygonMode(GL_FRONT, MaxwellToGL::PolygonMode(regs.polygon_mode_front));
  1155. }
  1156. if (flags[Dirty::PolygonModeBack]) {
  1157. flags[Dirty::PolygonModeBack] = false;
  1158. glPolygonMode(GL_BACK, MaxwellToGL::PolygonMode(regs.polygon_mode_back));
  1159. }
  1160. }
  1161. void RasterizerOpenGL::SyncColorMask() {
  1162. auto& flags = maxwell3d.dirty.flags;
  1163. if (!flags[Dirty::ColorMasks]) {
  1164. return;
  1165. }
  1166. flags[Dirty::ColorMasks] = false;
  1167. const bool force = flags[Dirty::ColorMaskCommon];
  1168. flags[Dirty::ColorMaskCommon] = false;
  1169. const auto& regs = maxwell3d.regs;
  1170. if (regs.color_mask_common) {
  1171. if (!force && !flags[Dirty::ColorMask0]) {
  1172. return;
  1173. }
  1174. flags[Dirty::ColorMask0] = false;
  1175. auto& mask = regs.color_mask[0];
  1176. glColorMask(mask.R != 0, mask.B != 0, mask.G != 0, mask.A != 0);
  1177. return;
  1178. }
  1179. // Path without color_mask_common set
  1180. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  1181. if (!force && !flags[Dirty::ColorMask0 + i]) {
  1182. continue;
  1183. }
  1184. flags[Dirty::ColorMask0 + i] = false;
  1185. const auto& mask = regs.color_mask[i];
  1186. glColorMaski(static_cast<GLuint>(i), mask.R != 0, mask.G != 0, mask.B != 0, mask.A != 0);
  1187. }
  1188. }
  1189. void RasterizerOpenGL::SyncMultiSampleState() {
  1190. auto& flags = maxwell3d.dirty.flags;
  1191. if (!flags[Dirty::MultisampleControl]) {
  1192. return;
  1193. }
  1194. flags[Dirty::MultisampleControl] = false;
  1195. const auto& regs = maxwell3d.regs;
  1196. oglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE, regs.multisample_control.alpha_to_coverage);
  1197. oglEnable(GL_SAMPLE_ALPHA_TO_ONE, regs.multisample_control.alpha_to_one);
  1198. }
  1199. void RasterizerOpenGL::SyncFragmentColorClampState() {
  1200. auto& flags = maxwell3d.dirty.flags;
  1201. if (!flags[Dirty::FragmentClampColor]) {
  1202. return;
  1203. }
  1204. flags[Dirty::FragmentClampColor] = false;
  1205. glClampColor(GL_CLAMP_FRAGMENT_COLOR, maxwell3d.regs.frag_color_clamp ? GL_TRUE : GL_FALSE);
  1206. }
  1207. void RasterizerOpenGL::SyncBlendState() {
  1208. auto& flags = maxwell3d.dirty.flags;
  1209. const auto& regs = maxwell3d.regs;
  1210. if (flags[Dirty::BlendColor]) {
  1211. flags[Dirty::BlendColor] = false;
  1212. glBlendColor(regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  1213. regs.blend_color.a);
  1214. }
  1215. // TODO(Rodrigo): Revisit blending, there are several registers we are not reading
  1216. if (!flags[Dirty::BlendStates]) {
  1217. return;
  1218. }
  1219. flags[Dirty::BlendStates] = false;
  1220. if (!regs.independent_blend_enable) {
  1221. if (!regs.blend.enable[0]) {
  1222. glDisable(GL_BLEND);
  1223. return;
  1224. }
  1225. glEnable(GL_BLEND);
  1226. glBlendFuncSeparate(MaxwellToGL::BlendFunc(regs.blend.factor_source_rgb),
  1227. MaxwellToGL::BlendFunc(regs.blend.factor_dest_rgb),
  1228. MaxwellToGL::BlendFunc(regs.blend.factor_source_a),
  1229. MaxwellToGL::BlendFunc(regs.blend.factor_dest_a));
  1230. glBlendEquationSeparate(MaxwellToGL::BlendEquation(regs.blend.equation_rgb),
  1231. MaxwellToGL::BlendEquation(regs.blend.equation_a));
  1232. return;
  1233. }
  1234. const bool force = flags[Dirty::BlendIndependentEnabled];
  1235. flags[Dirty::BlendIndependentEnabled] = false;
  1236. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  1237. if (!force && !flags[Dirty::BlendState0 + i]) {
  1238. continue;
  1239. }
  1240. flags[Dirty::BlendState0 + i] = false;
  1241. if (!regs.blend.enable[i]) {
  1242. glDisablei(GL_BLEND, static_cast<GLuint>(i));
  1243. continue;
  1244. }
  1245. glEnablei(GL_BLEND, static_cast<GLuint>(i));
  1246. const auto& src = regs.independent_blend[i];
  1247. glBlendFuncSeparatei(static_cast<GLuint>(i), MaxwellToGL::BlendFunc(src.factor_source_rgb),
  1248. MaxwellToGL::BlendFunc(src.factor_dest_rgb),
  1249. MaxwellToGL::BlendFunc(src.factor_source_a),
  1250. MaxwellToGL::BlendFunc(src.factor_dest_a));
  1251. glBlendEquationSeparatei(static_cast<GLuint>(i),
  1252. MaxwellToGL::BlendEquation(src.equation_rgb),
  1253. MaxwellToGL::BlendEquation(src.equation_a));
  1254. }
  1255. }
  1256. void RasterizerOpenGL::SyncLogicOpState() {
  1257. auto& flags = maxwell3d.dirty.flags;
  1258. if (!flags[Dirty::LogicOp]) {
  1259. return;
  1260. }
  1261. flags[Dirty::LogicOp] = false;
  1262. const auto& regs = maxwell3d.regs;
  1263. if (regs.logic_op.enable) {
  1264. glEnable(GL_COLOR_LOGIC_OP);
  1265. glLogicOp(MaxwellToGL::LogicOp(regs.logic_op.operation));
  1266. } else {
  1267. glDisable(GL_COLOR_LOGIC_OP);
  1268. }
  1269. }
  1270. void RasterizerOpenGL::SyncScissorTest() {
  1271. auto& flags = maxwell3d.dirty.flags;
  1272. if (!flags[Dirty::Scissors]) {
  1273. return;
  1274. }
  1275. flags[Dirty::Scissors] = false;
  1276. const auto& regs = maxwell3d.regs;
  1277. for (std::size_t index = 0; index < Maxwell::NumViewports; ++index) {
  1278. if (!flags[Dirty::Scissor0 + index]) {
  1279. continue;
  1280. }
  1281. flags[Dirty::Scissor0 + index] = false;
  1282. const auto& src = regs.scissor_test[index];
  1283. if (src.enable) {
  1284. glEnablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  1285. glScissorIndexed(static_cast<GLuint>(index), src.min_x, src.min_y,
  1286. src.max_x - src.min_x, src.max_y - src.min_y);
  1287. } else {
  1288. glDisablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  1289. }
  1290. }
  1291. }
  1292. void RasterizerOpenGL::SyncPointState() {
  1293. auto& flags = maxwell3d.dirty.flags;
  1294. if (!flags[Dirty::PointSize]) {
  1295. return;
  1296. }
  1297. flags[Dirty::PointSize] = false;
  1298. oglEnable(GL_POINT_SPRITE, maxwell3d.regs.point_sprite_enable);
  1299. if (maxwell3d.regs.vp_point_size.enable) {
  1300. // By definition of GL_POINT_SIZE, it only matters if GL_PROGRAM_POINT_SIZE is disabled.
  1301. glEnable(GL_PROGRAM_POINT_SIZE);
  1302. return;
  1303. }
  1304. // Limit the point size to 1 since nouveau sometimes sets a point size of 0 (and that's invalid
  1305. // in OpenGL).
  1306. glPointSize(std::max(1.0f, maxwell3d.regs.point_size));
  1307. glDisable(GL_PROGRAM_POINT_SIZE);
  1308. }
  1309. void RasterizerOpenGL::SyncLineState() {
  1310. auto& flags = maxwell3d.dirty.flags;
  1311. if (!flags[Dirty::LineWidth]) {
  1312. return;
  1313. }
  1314. flags[Dirty::LineWidth] = false;
  1315. const auto& regs = maxwell3d.regs;
  1316. oglEnable(GL_LINE_SMOOTH, regs.line_smooth_enable);
  1317. glLineWidth(regs.line_smooth_enable ? regs.line_width_smooth : regs.line_width_aliased);
  1318. }
  1319. void RasterizerOpenGL::SyncPolygonOffset() {
  1320. auto& flags = maxwell3d.dirty.flags;
  1321. if (!flags[Dirty::PolygonOffset]) {
  1322. return;
  1323. }
  1324. flags[Dirty::PolygonOffset] = false;
  1325. const auto& regs = maxwell3d.regs;
  1326. oglEnable(GL_POLYGON_OFFSET_FILL, regs.polygon_offset_fill_enable);
  1327. oglEnable(GL_POLYGON_OFFSET_LINE, regs.polygon_offset_line_enable);
  1328. oglEnable(GL_POLYGON_OFFSET_POINT, regs.polygon_offset_point_enable);
  1329. if (regs.polygon_offset_fill_enable || regs.polygon_offset_line_enable ||
  1330. regs.polygon_offset_point_enable) {
  1331. // Hardware divides polygon offset units by two
  1332. glPolygonOffsetClamp(regs.polygon_offset_factor, regs.polygon_offset_units / 2.0f,
  1333. regs.polygon_offset_clamp);
  1334. }
  1335. }
  1336. void RasterizerOpenGL::SyncAlphaTest() {
  1337. auto& flags = maxwell3d.dirty.flags;
  1338. if (!flags[Dirty::AlphaTest]) {
  1339. return;
  1340. }
  1341. flags[Dirty::AlphaTest] = false;
  1342. const auto& regs = maxwell3d.regs;
  1343. if (regs.alpha_test_enabled) {
  1344. glEnable(GL_ALPHA_TEST);
  1345. glAlphaFunc(MaxwellToGL::ComparisonOp(regs.alpha_test_func), regs.alpha_test_ref);
  1346. } else {
  1347. glDisable(GL_ALPHA_TEST);
  1348. }
  1349. }
  1350. void RasterizerOpenGL::SyncFramebufferSRGB() {
  1351. auto& flags = maxwell3d.dirty.flags;
  1352. if (!flags[Dirty::FramebufferSRGB]) {
  1353. return;
  1354. }
  1355. flags[Dirty::FramebufferSRGB] = false;
  1356. oglEnable(GL_FRAMEBUFFER_SRGB, maxwell3d.regs.framebuffer_srgb);
  1357. }
  1358. void RasterizerOpenGL::SyncTransformFeedback() {
  1359. // TODO(Rodrigo): Inject SKIP_COMPONENTS*_NV when required. An unimplemented message will signal
  1360. // when this is required.
  1361. const auto& regs = maxwell3d.regs;
  1362. static constexpr std::size_t STRIDE = 3;
  1363. std::array<GLint, 128 * STRIDE * Maxwell::NumTransformFeedbackBuffers> attribs;
  1364. std::array<GLint, Maxwell::NumTransformFeedbackBuffers> streams;
  1365. GLint* cursor = attribs.data();
  1366. GLint* current_stream = streams.data();
  1367. for (std::size_t feedback = 0; feedback < Maxwell::NumTransformFeedbackBuffers; ++feedback) {
  1368. const auto& layout = regs.tfb_layouts[feedback];
  1369. UNIMPLEMENTED_IF_MSG(layout.stride != layout.varying_count * 4, "Stride padding");
  1370. if (layout.varying_count == 0) {
  1371. continue;
  1372. }
  1373. *current_stream = static_cast<GLint>(feedback);
  1374. if (current_stream != streams.data()) {
  1375. // When stepping one stream, push the expected token
  1376. cursor[0] = GL_NEXT_BUFFER_NV;
  1377. cursor[1] = 0;
  1378. cursor[2] = 0;
  1379. cursor += STRIDE;
  1380. }
  1381. ++current_stream;
  1382. const auto& locations = regs.tfb_varying_locs[feedback];
  1383. std::optional<u8> current_index;
  1384. for (u32 offset = 0; offset < layout.varying_count; ++offset) {
  1385. const u8 location = locations[offset];
  1386. const u8 index = location / 4;
  1387. if (current_index == index) {
  1388. // Increase number of components of the previous attachment
  1389. ++cursor[-2];
  1390. continue;
  1391. }
  1392. current_index = index;
  1393. std::tie(cursor[0], cursor[2]) = TransformFeedbackEnum(location);
  1394. cursor[1] = 1;
  1395. cursor += STRIDE;
  1396. }
  1397. }
  1398. const GLsizei num_attribs = static_cast<GLsizei>((cursor - attribs.data()) / STRIDE);
  1399. const GLsizei num_strides = static_cast<GLsizei>(current_stream - streams.data());
  1400. glTransformFeedbackStreamAttribsNV(num_attribs, attribs.data(), num_strides, streams.data(),
  1401. GL_INTERLEAVED_ATTRIBS);
  1402. }
  1403. void RasterizerOpenGL::BeginTransformFeedback(GLenum primitive_mode) {
  1404. const auto& regs = maxwell3d.regs;
  1405. if (regs.tfb_enabled == 0) {
  1406. return;
  1407. }
  1408. if (device.UseAssemblyShaders()) {
  1409. SyncTransformFeedback();
  1410. }
  1411. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationControl) ||
  1412. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationEval) ||
  1413. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::Geometry));
  1414. for (std::size_t index = 0; index < Maxwell::NumTransformFeedbackBuffers; ++index) {
  1415. const auto& binding = regs.tfb_bindings[index];
  1416. if (!binding.buffer_enable) {
  1417. if (enabled_transform_feedback_buffers[index]) {
  1418. glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, static_cast<GLuint>(index), 0, 0,
  1419. 0);
  1420. }
  1421. enabled_transform_feedback_buffers[index] = false;
  1422. continue;
  1423. }
  1424. enabled_transform_feedback_buffers[index] = true;
  1425. auto& tfb_buffer = transform_feedback_buffers[index];
  1426. tfb_buffer.Create();
  1427. const GLuint handle = tfb_buffer.handle;
  1428. const std::size_t size = binding.buffer_size;
  1429. glNamedBufferData(handle, static_cast<GLsizeiptr>(size), nullptr, GL_STREAM_COPY);
  1430. glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, static_cast<GLuint>(index), handle, 0,
  1431. static_cast<GLsizeiptr>(size));
  1432. }
  1433. // We may have to call BeginTransformFeedbackNV here since they seem to call different
  1434. // implementations on Nvidia's driver (the pointer is different) but we are using
  1435. // ARB_transform_feedback3 features with NV_transform_feedback interactions and the ARB
  1436. // extension doesn't define BeginTransformFeedback (without NV) interactions. It just works.
  1437. glBeginTransformFeedback(GL_POINTS);
  1438. }
  1439. void RasterizerOpenGL::EndTransformFeedback() {
  1440. const auto& regs = maxwell3d.regs;
  1441. if (regs.tfb_enabled == 0) {
  1442. return;
  1443. }
  1444. glEndTransformFeedback();
  1445. for (std::size_t index = 0; index < Maxwell::NumTransformFeedbackBuffers; ++index) {
  1446. const auto& binding = regs.tfb_bindings[index];
  1447. if (!binding.buffer_enable) {
  1448. continue;
  1449. }
  1450. UNIMPLEMENTED_IF(binding.buffer_offset != 0);
  1451. const GLuint handle = transform_feedback_buffers[index].handle;
  1452. const GPUVAddr gpu_addr = binding.Address();
  1453. const std::size_t size = binding.buffer_size;
  1454. const auto info = buffer_cache.UploadMemory(gpu_addr, size, 4, true);
  1455. glCopyNamedBufferSubData(handle, info.handle, 0, info.offset,
  1456. static_cast<GLsizeiptr>(size));
  1457. }
  1458. }
  1459. } // namespace OpenGL