gl_rasterizer.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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 "common/settings.h"
  20. #include "core/core.h"
  21. #include "core/hle/kernel/k_process.h"
  22. #include "core/memory.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_device.h"
  28. #include "video_core/renderer_opengl/gl_query_cache.h"
  29. #include "video_core/renderer_opengl/gl_rasterizer.h"
  30. #include "video_core/renderer_opengl/gl_shader_cache.h"
  31. #include "video_core/renderer_opengl/gl_texture_cache.h"
  32. #include "video_core/renderer_opengl/maxwell_to_gl.h"
  33. #include "video_core/renderer_opengl/renderer_opengl.h"
  34. #include "video_core/shader_cache.h"
  35. #include "video_core/texture_cache/texture_cache.h"
  36. namespace OpenGL {
  37. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  38. using GLvec4 = std::array<GLfloat, 4>;
  39. using Tegra::Engines::ShaderType;
  40. using VideoCore::Surface::PixelFormat;
  41. using VideoCore::Surface::SurfaceTarget;
  42. using VideoCore::Surface::SurfaceType;
  43. MICROPROFILE_DEFINE(OpenGL_Drawing, "OpenGL", "Drawing", MP_RGB(128, 128, 192));
  44. MICROPROFILE_DEFINE(OpenGL_Clears, "OpenGL", "Clears", MP_RGB(128, 128, 192));
  45. MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(128, 128, 192));
  46. MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Management", MP_RGB(100, 255, 100));
  47. namespace {
  48. constexpr size_t NUM_SUPPORTED_VERTEX_ATTRIBUTES = 16;
  49. void oglEnable(GLenum cap, bool state) {
  50. (state ? glEnable : glDisable)(cap);
  51. }
  52. } // Anonymous namespace
  53. RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& emu_window_, Tegra::GPU& gpu_,
  54. Core::Memory::Memory& cpu_memory_, const Device& device_,
  55. ScreenInfo& screen_info_, ProgramManager& program_manager_,
  56. StateTracker& state_tracker_)
  57. : RasterizerAccelerated(cpu_memory_), gpu(gpu_), maxwell3d(gpu.Maxwell3D()),
  58. kepler_compute(gpu.KeplerCompute()), gpu_memory(gpu.MemoryManager()), device(device_),
  59. screen_info(screen_info_), program_manager(program_manager_), state_tracker(state_tracker_),
  60. texture_cache_runtime(device, program_manager, state_tracker),
  61. texture_cache(texture_cache_runtime, *this, maxwell3d, kepler_compute, gpu_memory),
  62. buffer_cache_runtime(device),
  63. buffer_cache(*this, maxwell3d, kepler_compute, gpu_memory, cpu_memory_, buffer_cache_runtime),
  64. shader_cache(*this, emu_window_, maxwell3d, kepler_compute, gpu_memory, device, texture_cache,
  65. buffer_cache, program_manager, state_tracker),
  66. query_cache(*this, maxwell3d, gpu_memory), accelerate_dma(buffer_cache),
  67. fence_manager(*this, gpu, texture_cache, buffer_cache, query_cache) {}
  68. RasterizerOpenGL::~RasterizerOpenGL() = default;
  69. void RasterizerOpenGL::SyncVertexFormats() {
  70. auto& flags = maxwell3d.dirty.flags;
  71. if (!flags[Dirty::VertexFormats]) {
  72. return;
  73. }
  74. flags[Dirty::VertexFormats] = false;
  75. // Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL. Enables
  76. // the first 16 vertex attributes always, as we don't know which ones are actually used until
  77. // shader time. Note, Tegra technically supports 32, but we're capping this to 16 for now to
  78. // avoid OpenGL errors.
  79. // TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
  80. // assume every shader uses them all.
  81. for (std::size_t index = 0; index < NUM_SUPPORTED_VERTEX_ATTRIBUTES; ++index) {
  82. if (!flags[Dirty::VertexFormat0 + index]) {
  83. continue;
  84. }
  85. flags[Dirty::VertexFormat0 + index] = false;
  86. const auto attrib = maxwell3d.regs.vertex_attrib_format[index];
  87. const auto gl_index = static_cast<GLuint>(index);
  88. // Disable constant attributes.
  89. if (attrib.IsConstant()) {
  90. glDisableVertexAttribArray(gl_index);
  91. continue;
  92. }
  93. glEnableVertexAttribArray(gl_index);
  94. if (attrib.type == Maxwell::VertexAttribute::Type::SignedInt ||
  95. attrib.type == Maxwell::VertexAttribute::Type::UnsignedInt) {
  96. glVertexAttribIFormat(gl_index, attrib.ComponentCount(),
  97. MaxwellToGL::VertexFormat(attrib), attrib.offset);
  98. } else {
  99. glVertexAttribFormat(gl_index, attrib.ComponentCount(),
  100. MaxwellToGL::VertexFormat(attrib),
  101. attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
  102. }
  103. glVertexAttribBinding(gl_index, attrib.buffer);
  104. }
  105. }
  106. void RasterizerOpenGL::SyncVertexInstances() {
  107. auto& flags = maxwell3d.dirty.flags;
  108. if (!flags[Dirty::VertexInstances]) {
  109. return;
  110. }
  111. flags[Dirty::VertexInstances] = false;
  112. const auto& regs = maxwell3d.regs;
  113. for (std::size_t index = 0; index < NUM_SUPPORTED_VERTEX_ATTRIBUTES; ++index) {
  114. if (!flags[Dirty::VertexInstance0 + index]) {
  115. continue;
  116. }
  117. flags[Dirty::VertexInstance0 + index] = false;
  118. const auto gl_index = static_cast<GLuint>(index);
  119. const bool instancing_enabled = regs.instanced_arrays.IsInstancingEnabled(gl_index);
  120. const GLuint divisor = instancing_enabled ? regs.vertex_array[index].divisor : 0;
  121. glVertexBindingDivisor(gl_index, divisor);
  122. }
  123. }
  124. void RasterizerOpenGL::LoadDiskResources(u64 title_id, std::stop_token stop_loading,
  125. const VideoCore::DiskResourceLoadCallback& callback) {
  126. shader_cache.LoadDiskResources(title_id, stop_loading, callback);
  127. }
  128. void RasterizerOpenGL::Clear() {
  129. MICROPROFILE_SCOPE(OpenGL_Clears);
  130. if (!maxwell3d.ShouldExecute()) {
  131. return;
  132. }
  133. const auto& regs = maxwell3d.regs;
  134. bool use_color{};
  135. bool use_depth{};
  136. bool use_stencil{};
  137. if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
  138. regs.clear_buffers.A) {
  139. use_color = true;
  140. const GLuint index = regs.clear_buffers.RT;
  141. state_tracker.NotifyColorMask(index);
  142. glColorMaski(index, regs.clear_buffers.R != 0, regs.clear_buffers.G != 0,
  143. regs.clear_buffers.B != 0, regs.clear_buffers.A != 0);
  144. // TODO(Rodrigo): Determine if clamping is used on clears
  145. SyncFragmentColorClampState();
  146. SyncFramebufferSRGB();
  147. }
  148. if (regs.clear_buffers.Z) {
  149. ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
  150. use_depth = true;
  151. state_tracker.NotifyDepthMask();
  152. glDepthMask(GL_TRUE);
  153. }
  154. if (regs.clear_buffers.S) {
  155. ASSERT_MSG(regs.zeta_enable, "Tried to clear stencil but buffer is not enabled!");
  156. use_stencil = true;
  157. }
  158. if (!use_color && !use_depth && !use_stencil) {
  159. // No color surface nor depth/stencil surface are enabled
  160. return;
  161. }
  162. SyncRasterizeEnable();
  163. SyncStencilTestState();
  164. if (regs.clear_flags.scissor) {
  165. SyncScissorTest();
  166. } else {
  167. state_tracker.NotifyScissor0();
  168. glDisablei(GL_SCISSOR_TEST, 0);
  169. }
  170. UNIMPLEMENTED_IF(regs.clear_flags.viewport);
  171. std::scoped_lock lock{texture_cache.mutex};
  172. texture_cache.UpdateRenderTargets(true);
  173. state_tracker.BindFramebuffer(texture_cache.GetFramebuffer()->Handle());
  174. if (use_color) {
  175. glClearBufferfv(GL_COLOR, regs.clear_buffers.RT, regs.clear_color);
  176. }
  177. if (use_depth && use_stencil) {
  178. glClearBufferfi(GL_DEPTH_STENCIL, 0, regs.clear_depth, regs.clear_stencil);
  179. } else if (use_depth) {
  180. glClearBufferfv(GL_DEPTH, 0, &regs.clear_depth);
  181. } else if (use_stencil) {
  182. glClearBufferiv(GL_STENCIL, 0, &regs.clear_stencil);
  183. }
  184. ++num_queued_commands;
  185. }
  186. void RasterizerOpenGL::Draw(bool is_indexed, bool is_instanced) {
  187. MICROPROFILE_SCOPE(OpenGL_Drawing);
  188. query_cache.UpdateCounters();
  189. SyncState();
  190. GraphicsPipeline* const pipeline{shader_cache.CurrentGraphicsPipeline()};
  191. if (!pipeline) {
  192. return;
  193. }
  194. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  195. pipeline->Configure(is_indexed);
  196. const GLenum primitive_mode = MaxwellToGL::PrimitiveTopology(maxwell3d.regs.draw.topology);
  197. BeginTransformFeedback(pipeline, primitive_mode);
  198. const GLuint base_instance = static_cast<GLuint>(maxwell3d.regs.vb_base_instance);
  199. const GLsizei num_instances =
  200. static_cast<GLsizei>(is_instanced ? maxwell3d.mme_draw.instance_count : 1);
  201. if (is_indexed) {
  202. const GLint base_vertex = static_cast<GLint>(maxwell3d.regs.vb_element_base);
  203. const GLsizei num_vertices = static_cast<GLsizei>(maxwell3d.regs.index_array.count);
  204. const GLvoid* const offset = buffer_cache_runtime.IndexOffset();
  205. const GLenum format = MaxwellToGL::IndexFormat(maxwell3d.regs.index_array.format);
  206. if (num_instances == 1 && base_instance == 0 && base_vertex == 0) {
  207. glDrawElements(primitive_mode, num_vertices, format, offset);
  208. } else if (num_instances == 1 && base_instance == 0) {
  209. glDrawElementsBaseVertex(primitive_mode, num_vertices, format, offset, base_vertex);
  210. } else if (base_vertex == 0 && base_instance == 0) {
  211. glDrawElementsInstanced(primitive_mode, num_vertices, format, offset, num_instances);
  212. } else if (base_vertex == 0) {
  213. glDrawElementsInstancedBaseInstance(primitive_mode, num_vertices, format, offset,
  214. num_instances, base_instance);
  215. } else if (base_instance == 0) {
  216. glDrawElementsInstancedBaseVertex(primitive_mode, num_vertices, format, offset,
  217. num_instances, base_vertex);
  218. } else {
  219. glDrawElementsInstancedBaseVertexBaseInstance(primitive_mode, num_vertices, format,
  220. offset, num_instances, base_vertex,
  221. base_instance);
  222. }
  223. } else {
  224. const GLint base_vertex = static_cast<GLint>(maxwell3d.regs.vertex_buffer.first);
  225. const GLsizei num_vertices = static_cast<GLsizei>(maxwell3d.regs.vertex_buffer.count);
  226. if (num_instances == 1 && base_instance == 0) {
  227. glDrawArrays(primitive_mode, base_vertex, num_vertices);
  228. } else if (base_instance == 0) {
  229. glDrawArraysInstanced(primitive_mode, base_vertex, num_vertices, num_instances);
  230. } else {
  231. glDrawArraysInstancedBaseInstance(primitive_mode, base_vertex, num_vertices,
  232. num_instances, base_instance);
  233. }
  234. }
  235. EndTransformFeedback();
  236. ++num_queued_commands;
  237. has_written_global_memory |= pipeline->WritesGlobalMemory();
  238. gpu.TickWork();
  239. }
  240. void RasterizerOpenGL::DispatchCompute() {
  241. ComputePipeline* const pipeline{shader_cache.CurrentComputePipeline()};
  242. if (!pipeline) {
  243. return;
  244. }
  245. pipeline->Configure();
  246. const auto& qmd{kepler_compute.launch_description};
  247. glDispatchCompute(qmd.grid_dim_x, qmd.grid_dim_y, qmd.grid_dim_z);
  248. ++num_queued_commands;
  249. has_written_global_memory |= pipeline->WritesGlobalMemory();
  250. }
  251. void RasterizerOpenGL::ResetCounter(VideoCore::QueryType type) {
  252. query_cache.ResetCounter(type);
  253. }
  254. void RasterizerOpenGL::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
  255. std::optional<u64> timestamp) {
  256. query_cache.Query(gpu_addr, type, timestamp);
  257. }
  258. void RasterizerOpenGL::BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr,
  259. u32 size) {
  260. std::scoped_lock lock{buffer_cache.mutex};
  261. buffer_cache.BindGraphicsUniformBuffer(stage, index, gpu_addr, size);
  262. }
  263. void RasterizerOpenGL::DisableGraphicsUniformBuffer(size_t stage, u32 index) {
  264. buffer_cache.DisableGraphicsUniformBuffer(stage, index);
  265. }
  266. void RasterizerOpenGL::FlushAll() {}
  267. void RasterizerOpenGL::FlushRegion(VAddr addr, u64 size) {
  268. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  269. if (addr == 0 || size == 0) {
  270. return;
  271. }
  272. {
  273. std::scoped_lock lock{texture_cache.mutex};
  274. texture_cache.DownloadMemory(addr, size);
  275. }
  276. {
  277. std::scoped_lock lock{buffer_cache.mutex};
  278. buffer_cache.DownloadMemory(addr, size);
  279. }
  280. query_cache.FlushRegion(addr, size);
  281. }
  282. bool RasterizerOpenGL::MustFlushRegion(VAddr addr, u64 size) {
  283. std::scoped_lock lock{buffer_cache.mutex, texture_cache.mutex};
  284. if (!Settings::IsGPULevelHigh()) {
  285. return buffer_cache.IsRegionGpuModified(addr, size);
  286. }
  287. return texture_cache.IsRegionGpuModified(addr, size) ||
  288. buffer_cache.IsRegionGpuModified(addr, size);
  289. }
  290. void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size) {
  291. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  292. if (addr == 0 || size == 0) {
  293. return;
  294. }
  295. {
  296. std::scoped_lock lock{texture_cache.mutex};
  297. texture_cache.WriteMemory(addr, size);
  298. }
  299. {
  300. std::scoped_lock lock{buffer_cache.mutex};
  301. buffer_cache.WriteMemory(addr, size);
  302. }
  303. shader_cache.InvalidateRegion(addr, size);
  304. query_cache.InvalidateRegion(addr, size);
  305. }
  306. void RasterizerOpenGL::OnCPUWrite(VAddr addr, u64 size) {
  307. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  308. if (addr == 0 || size == 0) {
  309. return;
  310. }
  311. shader_cache.OnCPUWrite(addr, size);
  312. {
  313. std::scoped_lock lock{texture_cache.mutex};
  314. texture_cache.WriteMemory(addr, size);
  315. }
  316. {
  317. std::scoped_lock lock{buffer_cache.mutex};
  318. buffer_cache.CachedWriteMemory(addr, size);
  319. }
  320. }
  321. void RasterizerOpenGL::SyncGuestHost() {
  322. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  323. shader_cache.SyncGuestHost();
  324. {
  325. std::scoped_lock lock{buffer_cache.mutex};
  326. buffer_cache.FlushCachedWrites();
  327. }
  328. }
  329. void RasterizerOpenGL::UnmapMemory(VAddr addr, u64 size) {
  330. {
  331. std::scoped_lock lock{texture_cache.mutex};
  332. texture_cache.UnmapMemory(addr, size);
  333. }
  334. {
  335. std::scoped_lock lock{buffer_cache.mutex};
  336. buffer_cache.WriteMemory(addr, size);
  337. }
  338. shader_cache.OnCPUWrite(addr, size);
  339. }
  340. void RasterizerOpenGL::ModifyGPUMemory(GPUVAddr addr, u64 size) {
  341. {
  342. std::scoped_lock lock{texture_cache.mutex};
  343. texture_cache.UnmapGPUMemory(addr, size);
  344. }
  345. }
  346. void RasterizerOpenGL::SignalSemaphore(GPUVAddr addr, u32 value) {
  347. if (!gpu.IsAsync()) {
  348. gpu_memory.Write<u32>(addr, value);
  349. return;
  350. }
  351. fence_manager.SignalSemaphore(addr, value);
  352. }
  353. void RasterizerOpenGL::SignalSyncPoint(u32 value) {
  354. if (!gpu.IsAsync()) {
  355. gpu.IncrementSyncPoint(value);
  356. return;
  357. }
  358. fence_manager.SignalSyncPoint(value);
  359. }
  360. void RasterizerOpenGL::SignalReference() {
  361. if (!gpu.IsAsync()) {
  362. return;
  363. }
  364. fence_manager.SignalOrdering();
  365. }
  366. void RasterizerOpenGL::ReleaseFences() {
  367. if (!gpu.IsAsync()) {
  368. return;
  369. }
  370. fence_manager.WaitPendingFences();
  371. }
  372. void RasterizerOpenGL::FlushAndInvalidateRegion(VAddr addr, u64 size) {
  373. if (Settings::IsGPULevelExtreme()) {
  374. FlushRegion(addr, size);
  375. }
  376. InvalidateRegion(addr, size);
  377. }
  378. void RasterizerOpenGL::WaitForIdle() {
  379. glMemoryBarrier(GL_ALL_BARRIER_BITS);
  380. SignalReference();
  381. }
  382. void RasterizerOpenGL::FragmentBarrier() {
  383. glMemoryBarrier(GL_FRAMEBUFFER_BARRIER_BIT | GL_TEXTURE_FETCH_BARRIER_BIT);
  384. }
  385. void RasterizerOpenGL::TiledCacheBarrier() {
  386. glTextureBarrier();
  387. }
  388. void RasterizerOpenGL::FlushCommands() {
  389. // Only flush when we have commands queued to OpenGL.
  390. if (num_queued_commands == 0) {
  391. return;
  392. }
  393. num_queued_commands = 0;
  394. // Make sure memory stored from the previous GL command stream is visible
  395. // This is only needed on assembly shaders where we write to GPU memory with raw pointers
  396. if (has_written_global_memory) {
  397. has_written_global_memory = false;
  398. glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT);
  399. }
  400. glFlush();
  401. }
  402. void RasterizerOpenGL::TickFrame() {
  403. // Ticking a frame means that buffers will be swapped, calling glFlush implicitly.
  404. num_queued_commands = 0;
  405. fence_manager.TickFrame();
  406. {
  407. std::scoped_lock lock{texture_cache.mutex};
  408. texture_cache.TickFrame();
  409. }
  410. {
  411. std::scoped_lock lock{buffer_cache.mutex};
  412. buffer_cache.TickFrame();
  413. }
  414. }
  415. bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Surface& src,
  416. const Tegra::Engines::Fermi2D::Surface& dst,
  417. const Tegra::Engines::Fermi2D::Config& copy_config) {
  418. MICROPROFILE_SCOPE(OpenGL_Blits);
  419. std::scoped_lock lock{texture_cache.mutex};
  420. texture_cache.BlitImage(dst, src, copy_config);
  421. return true;
  422. }
  423. Tegra::Engines::AccelerateDMAInterface& RasterizerOpenGL::AccessAccelerateDMA() {
  424. return accelerate_dma;
  425. }
  426. bool RasterizerOpenGL::AccelerateDisplay(const Tegra::FramebufferConfig& config,
  427. VAddr framebuffer_addr, u32 pixel_stride) {
  428. if (framebuffer_addr == 0) {
  429. return false;
  430. }
  431. MICROPROFILE_SCOPE(OpenGL_CacheManagement);
  432. std::scoped_lock lock{texture_cache.mutex};
  433. ImageView* const image_view{texture_cache.TryFindFramebufferImageView(framebuffer_addr)};
  434. if (!image_view) {
  435. return false;
  436. }
  437. // Verify that the cached surface is the same size and format as the requested framebuffer
  438. // ASSERT_MSG(image_view->size.width == config.width, "Framebuffer width is different");
  439. // ASSERT_MSG(image_view->size.height == config.height, "Framebuffer height is different");
  440. screen_info.display_texture = image_view->Handle(Shader::TextureType::Color2D);
  441. screen_info.display_srgb = VideoCore::Surface::IsPixelFormatSRGB(image_view->format);
  442. return true;
  443. }
  444. void RasterizerOpenGL::SyncState() {
  445. SyncViewport();
  446. SyncRasterizeEnable();
  447. SyncPolygonModes();
  448. SyncColorMask();
  449. SyncFragmentColorClampState();
  450. SyncMultiSampleState();
  451. SyncDepthTestState();
  452. SyncDepthClamp();
  453. SyncStencilTestState();
  454. SyncBlendState();
  455. SyncLogicOpState();
  456. SyncCullMode();
  457. SyncPrimitiveRestart();
  458. SyncScissorTest();
  459. SyncPointState();
  460. SyncLineState();
  461. SyncPolygonOffset();
  462. SyncAlphaTest();
  463. SyncFramebufferSRGB();
  464. SyncVertexFormats();
  465. SyncVertexInstances();
  466. }
  467. void RasterizerOpenGL::SyncViewport() {
  468. auto& flags = maxwell3d.dirty.flags;
  469. const auto& regs = maxwell3d.regs;
  470. const bool dirty_viewport = flags[Dirty::Viewports];
  471. const bool dirty_clip_control = flags[Dirty::ClipControl];
  472. if (dirty_clip_control || flags[Dirty::FrontFace]) {
  473. flags[Dirty::FrontFace] = false;
  474. GLenum mode = MaxwellToGL::FrontFace(regs.front_face);
  475. if (regs.screen_y_control.triangle_rast_flip != 0 &&
  476. regs.viewport_transform[0].scale_y < 0.0f) {
  477. switch (mode) {
  478. case GL_CW:
  479. mode = GL_CCW;
  480. break;
  481. case GL_CCW:
  482. mode = GL_CW;
  483. break;
  484. }
  485. }
  486. glFrontFace(mode);
  487. }
  488. if (dirty_viewport || flags[Dirty::ClipControl]) {
  489. flags[Dirty::ClipControl] = false;
  490. bool flip_y = false;
  491. if (regs.viewport_transform[0].scale_y < 0.0f) {
  492. flip_y = !flip_y;
  493. }
  494. if (regs.screen_y_control.y_negate != 0) {
  495. flip_y = !flip_y;
  496. }
  497. const bool is_zero_to_one = regs.depth_mode == Maxwell::DepthMode::ZeroToOne;
  498. const GLenum origin = flip_y ? GL_UPPER_LEFT : GL_LOWER_LEFT;
  499. const GLenum depth = is_zero_to_one ? GL_ZERO_TO_ONE : GL_NEGATIVE_ONE_TO_ONE;
  500. state_tracker.ClipControl(origin, depth);
  501. state_tracker.SetYNegate(regs.screen_y_control.y_negate != 0);
  502. }
  503. if (dirty_viewport) {
  504. flags[Dirty::Viewports] = false;
  505. const bool force = flags[Dirty::ViewportTransform];
  506. flags[Dirty::ViewportTransform] = false;
  507. for (std::size_t i = 0; i < Maxwell::NumViewports; ++i) {
  508. if (!force && !flags[Dirty::Viewport0 + i]) {
  509. continue;
  510. }
  511. flags[Dirty::Viewport0 + i] = false;
  512. const auto& src = regs.viewport_transform[i];
  513. const Common::Rectangle<f32> rect{src.GetRect()};
  514. glViewportIndexedf(static_cast<GLuint>(i), rect.left, rect.bottom, rect.GetWidth(),
  515. rect.GetHeight());
  516. const GLdouble reduce_z = regs.depth_mode == Maxwell::DepthMode::MinusOneToOne;
  517. const GLdouble near_depth = src.translate_z - src.scale_z * reduce_z;
  518. const GLdouble far_depth = src.translate_z + src.scale_z;
  519. if (device.HasDepthBufferFloat()) {
  520. glDepthRangeIndexeddNV(static_cast<GLuint>(i), near_depth, far_depth);
  521. } else {
  522. glDepthRangeIndexed(static_cast<GLuint>(i), near_depth, far_depth);
  523. }
  524. if (!GLAD_GL_NV_viewport_swizzle) {
  525. continue;
  526. }
  527. glViewportSwizzleNV(static_cast<GLuint>(i), MaxwellToGL::ViewportSwizzle(src.swizzle.x),
  528. MaxwellToGL::ViewportSwizzle(src.swizzle.y),
  529. MaxwellToGL::ViewportSwizzle(src.swizzle.z),
  530. MaxwellToGL::ViewportSwizzle(src.swizzle.w));
  531. }
  532. }
  533. }
  534. void RasterizerOpenGL::SyncDepthClamp() {
  535. auto& flags = maxwell3d.dirty.flags;
  536. if (!flags[Dirty::DepthClampEnabled]) {
  537. return;
  538. }
  539. flags[Dirty::DepthClampEnabled] = false;
  540. oglEnable(GL_DEPTH_CLAMP, maxwell3d.regs.view_volume_clip_control.depth_clamp_disabled == 0);
  541. }
  542. void RasterizerOpenGL::SyncClipEnabled(u32 clip_mask) {
  543. auto& flags = maxwell3d.dirty.flags;
  544. if (!flags[Dirty::ClipDistances] && !flags[VideoCommon::Dirty::Shaders]) {
  545. return;
  546. }
  547. flags[Dirty::ClipDistances] = false;
  548. clip_mask &= maxwell3d.regs.clip_distance_enabled;
  549. if (clip_mask == last_clip_distance_mask) {
  550. return;
  551. }
  552. last_clip_distance_mask = clip_mask;
  553. for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
  554. oglEnable(static_cast<GLenum>(GL_CLIP_DISTANCE0 + i), (clip_mask >> i) & 1);
  555. }
  556. }
  557. void RasterizerOpenGL::SyncClipCoef() {
  558. UNIMPLEMENTED();
  559. }
  560. void RasterizerOpenGL::SyncCullMode() {
  561. auto& flags = maxwell3d.dirty.flags;
  562. const auto& regs = maxwell3d.regs;
  563. if (flags[Dirty::CullTest]) {
  564. flags[Dirty::CullTest] = false;
  565. if (regs.cull_test_enabled) {
  566. glEnable(GL_CULL_FACE);
  567. glCullFace(MaxwellToGL::CullFace(regs.cull_face));
  568. } else {
  569. glDisable(GL_CULL_FACE);
  570. }
  571. }
  572. }
  573. void RasterizerOpenGL::SyncPrimitiveRestart() {
  574. auto& flags = maxwell3d.dirty.flags;
  575. if (!flags[Dirty::PrimitiveRestart]) {
  576. return;
  577. }
  578. flags[Dirty::PrimitiveRestart] = false;
  579. if (maxwell3d.regs.primitive_restart.enabled) {
  580. glEnable(GL_PRIMITIVE_RESTART);
  581. glPrimitiveRestartIndex(maxwell3d.regs.primitive_restart.index);
  582. } else {
  583. glDisable(GL_PRIMITIVE_RESTART);
  584. }
  585. }
  586. void RasterizerOpenGL::SyncDepthTestState() {
  587. auto& flags = maxwell3d.dirty.flags;
  588. const auto& regs = maxwell3d.regs;
  589. if (flags[Dirty::DepthMask]) {
  590. flags[Dirty::DepthMask] = false;
  591. glDepthMask(regs.depth_write_enabled ? GL_TRUE : GL_FALSE);
  592. }
  593. if (flags[Dirty::DepthTest]) {
  594. flags[Dirty::DepthTest] = false;
  595. if (regs.depth_test_enable) {
  596. glEnable(GL_DEPTH_TEST);
  597. glDepthFunc(MaxwellToGL::ComparisonOp(regs.depth_test_func));
  598. } else {
  599. glDisable(GL_DEPTH_TEST);
  600. }
  601. }
  602. }
  603. void RasterizerOpenGL::SyncStencilTestState() {
  604. auto& flags = maxwell3d.dirty.flags;
  605. if (!flags[Dirty::StencilTest]) {
  606. return;
  607. }
  608. flags[Dirty::StencilTest] = false;
  609. const auto& regs = maxwell3d.regs;
  610. oglEnable(GL_STENCIL_TEST, regs.stencil_enable);
  611. glStencilFuncSeparate(GL_FRONT, MaxwellToGL::ComparisonOp(regs.stencil_front_func_func),
  612. regs.stencil_front_func_ref, regs.stencil_front_func_mask);
  613. glStencilOpSeparate(GL_FRONT, MaxwellToGL::StencilOp(regs.stencil_front_op_fail),
  614. MaxwellToGL::StencilOp(regs.stencil_front_op_zfail),
  615. MaxwellToGL::StencilOp(regs.stencil_front_op_zpass));
  616. glStencilMaskSeparate(GL_FRONT, regs.stencil_front_mask);
  617. if (regs.stencil_two_side_enable) {
  618. glStencilFuncSeparate(GL_BACK, MaxwellToGL::ComparisonOp(regs.stencil_back_func_func),
  619. regs.stencil_back_func_ref, regs.stencil_back_func_mask);
  620. glStencilOpSeparate(GL_BACK, MaxwellToGL::StencilOp(regs.stencil_back_op_fail),
  621. MaxwellToGL::StencilOp(regs.stencil_back_op_zfail),
  622. MaxwellToGL::StencilOp(regs.stencil_back_op_zpass));
  623. glStencilMaskSeparate(GL_BACK, regs.stencil_back_mask);
  624. } else {
  625. glStencilFuncSeparate(GL_BACK, GL_ALWAYS, 0, 0xFFFFFFFF);
  626. glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP);
  627. glStencilMaskSeparate(GL_BACK, 0xFFFFFFFF);
  628. }
  629. }
  630. void RasterizerOpenGL::SyncRasterizeEnable() {
  631. auto& flags = maxwell3d.dirty.flags;
  632. if (!flags[Dirty::RasterizeEnable]) {
  633. return;
  634. }
  635. flags[Dirty::RasterizeEnable] = false;
  636. oglEnable(GL_RASTERIZER_DISCARD, maxwell3d.regs.rasterize_enable == 0);
  637. }
  638. void RasterizerOpenGL::SyncPolygonModes() {
  639. auto& flags = maxwell3d.dirty.flags;
  640. if (!flags[Dirty::PolygonModes]) {
  641. return;
  642. }
  643. flags[Dirty::PolygonModes] = false;
  644. const auto& regs = maxwell3d.regs;
  645. if (regs.fill_rectangle) {
  646. if (!GLAD_GL_NV_fill_rectangle) {
  647. LOG_ERROR(Render_OpenGL, "GL_NV_fill_rectangle used and not supported");
  648. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  649. return;
  650. }
  651. flags[Dirty::PolygonModeFront] = true;
  652. flags[Dirty::PolygonModeBack] = true;
  653. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL_RECTANGLE_NV);
  654. return;
  655. }
  656. if (regs.polygon_mode_front == regs.polygon_mode_back) {
  657. flags[Dirty::PolygonModeFront] = false;
  658. flags[Dirty::PolygonModeBack] = false;
  659. glPolygonMode(GL_FRONT_AND_BACK, MaxwellToGL::PolygonMode(regs.polygon_mode_front));
  660. return;
  661. }
  662. if (flags[Dirty::PolygonModeFront]) {
  663. flags[Dirty::PolygonModeFront] = false;
  664. glPolygonMode(GL_FRONT, MaxwellToGL::PolygonMode(regs.polygon_mode_front));
  665. }
  666. if (flags[Dirty::PolygonModeBack]) {
  667. flags[Dirty::PolygonModeBack] = false;
  668. glPolygonMode(GL_BACK, MaxwellToGL::PolygonMode(regs.polygon_mode_back));
  669. }
  670. }
  671. void RasterizerOpenGL::SyncColorMask() {
  672. auto& flags = maxwell3d.dirty.flags;
  673. if (!flags[Dirty::ColorMasks]) {
  674. return;
  675. }
  676. flags[Dirty::ColorMasks] = false;
  677. const bool force = flags[Dirty::ColorMaskCommon];
  678. flags[Dirty::ColorMaskCommon] = false;
  679. const auto& regs = maxwell3d.regs;
  680. if (regs.color_mask_common) {
  681. if (!force && !flags[Dirty::ColorMask0]) {
  682. return;
  683. }
  684. flags[Dirty::ColorMask0] = false;
  685. auto& mask = regs.color_mask[0];
  686. glColorMask(mask.R != 0, mask.B != 0, mask.G != 0, mask.A != 0);
  687. return;
  688. }
  689. // Path without color_mask_common set
  690. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  691. if (!force && !flags[Dirty::ColorMask0 + i]) {
  692. continue;
  693. }
  694. flags[Dirty::ColorMask0 + i] = false;
  695. const auto& mask = regs.color_mask[i];
  696. glColorMaski(static_cast<GLuint>(i), mask.R != 0, mask.G != 0, mask.B != 0, mask.A != 0);
  697. }
  698. }
  699. void RasterizerOpenGL::SyncMultiSampleState() {
  700. auto& flags = maxwell3d.dirty.flags;
  701. if (!flags[Dirty::MultisampleControl]) {
  702. return;
  703. }
  704. flags[Dirty::MultisampleControl] = false;
  705. const auto& regs = maxwell3d.regs;
  706. oglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE, regs.multisample_control.alpha_to_coverage);
  707. oglEnable(GL_SAMPLE_ALPHA_TO_ONE, regs.multisample_control.alpha_to_one);
  708. }
  709. void RasterizerOpenGL::SyncFragmentColorClampState() {
  710. auto& flags = maxwell3d.dirty.flags;
  711. if (!flags[Dirty::FragmentClampColor]) {
  712. return;
  713. }
  714. flags[Dirty::FragmentClampColor] = false;
  715. glClampColor(GL_CLAMP_FRAGMENT_COLOR, maxwell3d.regs.frag_color_clamp ? GL_TRUE : GL_FALSE);
  716. }
  717. void RasterizerOpenGL::SyncBlendState() {
  718. auto& flags = maxwell3d.dirty.flags;
  719. const auto& regs = maxwell3d.regs;
  720. if (flags[Dirty::BlendColor]) {
  721. flags[Dirty::BlendColor] = false;
  722. glBlendColor(regs.blend_color.r, regs.blend_color.g, regs.blend_color.b,
  723. regs.blend_color.a);
  724. }
  725. // TODO(Rodrigo): Revisit blending, there are several registers we are not reading
  726. if (!flags[Dirty::BlendStates]) {
  727. return;
  728. }
  729. flags[Dirty::BlendStates] = false;
  730. if (!regs.independent_blend_enable) {
  731. if (!regs.blend.enable[0]) {
  732. glDisable(GL_BLEND);
  733. return;
  734. }
  735. glEnable(GL_BLEND);
  736. glBlendFuncSeparate(MaxwellToGL::BlendFunc(regs.blend.factor_source_rgb),
  737. MaxwellToGL::BlendFunc(regs.blend.factor_dest_rgb),
  738. MaxwellToGL::BlendFunc(regs.blend.factor_source_a),
  739. MaxwellToGL::BlendFunc(regs.blend.factor_dest_a));
  740. glBlendEquationSeparate(MaxwellToGL::BlendEquation(regs.blend.equation_rgb),
  741. MaxwellToGL::BlendEquation(regs.blend.equation_a));
  742. return;
  743. }
  744. const bool force = flags[Dirty::BlendIndependentEnabled];
  745. flags[Dirty::BlendIndependentEnabled] = false;
  746. for (std::size_t i = 0; i < Maxwell::NumRenderTargets; ++i) {
  747. if (!force && !flags[Dirty::BlendState0 + i]) {
  748. continue;
  749. }
  750. flags[Dirty::BlendState0 + i] = false;
  751. if (!regs.blend.enable[i]) {
  752. glDisablei(GL_BLEND, static_cast<GLuint>(i));
  753. continue;
  754. }
  755. glEnablei(GL_BLEND, static_cast<GLuint>(i));
  756. const auto& src = regs.independent_blend[i];
  757. glBlendFuncSeparatei(static_cast<GLuint>(i), MaxwellToGL::BlendFunc(src.factor_source_rgb),
  758. MaxwellToGL::BlendFunc(src.factor_dest_rgb),
  759. MaxwellToGL::BlendFunc(src.factor_source_a),
  760. MaxwellToGL::BlendFunc(src.factor_dest_a));
  761. glBlendEquationSeparatei(static_cast<GLuint>(i),
  762. MaxwellToGL::BlendEquation(src.equation_rgb),
  763. MaxwellToGL::BlendEquation(src.equation_a));
  764. }
  765. }
  766. void RasterizerOpenGL::SyncLogicOpState() {
  767. auto& flags = maxwell3d.dirty.flags;
  768. if (!flags[Dirty::LogicOp]) {
  769. return;
  770. }
  771. flags[Dirty::LogicOp] = false;
  772. const auto& regs = maxwell3d.regs;
  773. if (regs.logic_op.enable) {
  774. glEnable(GL_COLOR_LOGIC_OP);
  775. glLogicOp(MaxwellToGL::LogicOp(regs.logic_op.operation));
  776. } else {
  777. glDisable(GL_COLOR_LOGIC_OP);
  778. }
  779. }
  780. void RasterizerOpenGL::SyncScissorTest() {
  781. auto& flags = maxwell3d.dirty.flags;
  782. if (!flags[Dirty::Scissors]) {
  783. return;
  784. }
  785. flags[Dirty::Scissors] = false;
  786. const auto& regs = maxwell3d.regs;
  787. for (std::size_t index = 0; index < Maxwell::NumViewports; ++index) {
  788. if (!flags[Dirty::Scissor0 + index]) {
  789. continue;
  790. }
  791. flags[Dirty::Scissor0 + index] = false;
  792. const auto& src = regs.scissor_test[index];
  793. if (src.enable) {
  794. glEnablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  795. glScissorIndexed(static_cast<GLuint>(index), src.min_x, src.min_y,
  796. src.max_x - src.min_x, src.max_y - src.min_y);
  797. } else {
  798. glDisablei(GL_SCISSOR_TEST, static_cast<GLuint>(index));
  799. }
  800. }
  801. }
  802. void RasterizerOpenGL::SyncPointState() {
  803. auto& flags = maxwell3d.dirty.flags;
  804. if (!flags[Dirty::PointSize]) {
  805. return;
  806. }
  807. flags[Dirty::PointSize] = false;
  808. oglEnable(GL_POINT_SPRITE, maxwell3d.regs.point_sprite_enable);
  809. oglEnable(GL_PROGRAM_POINT_SIZE, maxwell3d.regs.vp_point_size.enable);
  810. glPointSize(std::max(1.0f, maxwell3d.regs.point_size));
  811. }
  812. void RasterizerOpenGL::SyncLineState() {
  813. auto& flags = maxwell3d.dirty.flags;
  814. if (!flags[Dirty::LineWidth]) {
  815. return;
  816. }
  817. flags[Dirty::LineWidth] = false;
  818. const auto& regs = maxwell3d.regs;
  819. oglEnable(GL_LINE_SMOOTH, regs.line_smooth_enable);
  820. glLineWidth(regs.line_smooth_enable ? regs.line_width_smooth : regs.line_width_aliased);
  821. }
  822. void RasterizerOpenGL::SyncPolygonOffset() {
  823. auto& flags = maxwell3d.dirty.flags;
  824. if (!flags[Dirty::PolygonOffset]) {
  825. return;
  826. }
  827. flags[Dirty::PolygonOffset] = false;
  828. const auto& regs = maxwell3d.regs;
  829. oglEnable(GL_POLYGON_OFFSET_FILL, regs.polygon_offset_fill_enable);
  830. oglEnable(GL_POLYGON_OFFSET_LINE, regs.polygon_offset_line_enable);
  831. oglEnable(GL_POLYGON_OFFSET_POINT, regs.polygon_offset_point_enable);
  832. if (regs.polygon_offset_fill_enable || regs.polygon_offset_line_enable ||
  833. regs.polygon_offset_point_enable) {
  834. // Hardware divides polygon offset units by two
  835. glPolygonOffsetClamp(regs.polygon_offset_factor, regs.polygon_offset_units / 2.0f,
  836. regs.polygon_offset_clamp);
  837. }
  838. }
  839. void RasterizerOpenGL::SyncAlphaTest() {
  840. auto& flags = maxwell3d.dirty.flags;
  841. if (!flags[Dirty::AlphaTest]) {
  842. return;
  843. }
  844. flags[Dirty::AlphaTest] = false;
  845. const auto& regs = maxwell3d.regs;
  846. if (regs.alpha_test_enabled) {
  847. glEnable(GL_ALPHA_TEST);
  848. glAlphaFunc(MaxwellToGL::ComparisonOp(regs.alpha_test_func), regs.alpha_test_ref);
  849. } else {
  850. glDisable(GL_ALPHA_TEST);
  851. }
  852. }
  853. void RasterizerOpenGL::SyncFramebufferSRGB() {
  854. auto& flags = maxwell3d.dirty.flags;
  855. if (!flags[Dirty::FramebufferSRGB]) {
  856. return;
  857. }
  858. flags[Dirty::FramebufferSRGB] = false;
  859. oglEnable(GL_FRAMEBUFFER_SRGB, maxwell3d.regs.framebuffer_srgb);
  860. }
  861. void RasterizerOpenGL::BeginTransformFeedback(GraphicsPipeline* program, GLenum primitive_mode) {
  862. const auto& regs = maxwell3d.regs;
  863. if (regs.tfb_enabled == 0) {
  864. return;
  865. }
  866. program->ConfigureTransformFeedback();
  867. UNIMPLEMENTED_IF(regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationControl) ||
  868. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::TesselationEval) ||
  869. regs.IsShaderConfigEnabled(Maxwell::ShaderProgram::Geometry));
  870. UNIMPLEMENTED_IF(primitive_mode != GL_POINTS);
  871. // We may have to call BeginTransformFeedbackNV here since they seem to call different
  872. // implementations on Nvidia's driver (the pointer is different) but we are using
  873. // ARB_transform_feedback3 features with NV_transform_feedback interactions and the ARB
  874. // extension doesn't define BeginTransformFeedback (without NV) interactions. It just works.
  875. glBeginTransformFeedback(GL_POINTS);
  876. }
  877. void RasterizerOpenGL::EndTransformFeedback() {
  878. if (maxwell3d.regs.tfb_enabled != 0) {
  879. glEndTransformFeedback();
  880. }
  881. }
  882. AccelerateDMA::AccelerateDMA(BufferCache& buffer_cache_) : buffer_cache{buffer_cache_} {}
  883. bool AccelerateDMA::BufferCopy(GPUVAddr src_address, GPUVAddr dest_address, u64 amount) {
  884. std::scoped_lock lock{buffer_cache.mutex};
  885. return buffer_cache.DMACopy(src_address, dest_address, amount);
  886. }
  887. bool AccelerateDMA::BufferClear(GPUVAddr src_address, u64 amount, u32 value) {
  888. std::scoped_lock lock{buffer_cache.mutex};
  889. return buffer_cache.DMAClear(src_address, amount, value);
  890. }
  891. } // namespace OpenGL