renderer_opengl.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <cstddef>
  6. #include <cstdlib>
  7. #include <memory>
  8. #include <glad/glad.h>
  9. #include "common/assert.h"
  10. #include "common/logging/log.h"
  11. #include "common/microprofile.h"
  12. #include "common/telemetry.h"
  13. #include "core/core.h"
  14. #include "core/core_timing.h"
  15. #include "core/frontend/emu_window.h"
  16. #include "core/memory.h"
  17. #include "core/perf_stats.h"
  18. #include "core/settings.h"
  19. #include "core/telemetry_session.h"
  20. #include "video_core/morton.h"
  21. #include "video_core/renderer_opengl/gl_rasterizer.h"
  22. #include "video_core/renderer_opengl/renderer_opengl.h"
  23. namespace OpenGL {
  24. // If the size of this is too small, it ends up creating a soft cap on FPS as the renderer will have
  25. // to wait on available presentation frames.
  26. constexpr std::size_t SWAP_CHAIN_SIZE = 3;
  27. struct Frame {
  28. u32 width{}; /// Width of the frame (to detect resize)
  29. u32 height{}; /// Height of the frame
  30. bool color_reloaded{}; /// Texture attachment was recreated (ie: resized)
  31. OpenGL::OGLRenderbuffer color{}; /// Buffer shared between the render/present FBO
  32. OpenGL::OGLFramebuffer render{}; /// FBO created on the render thread
  33. OpenGL::OGLFramebuffer present{}; /// FBO created on the present thread
  34. GLsync render_fence{}; /// Fence created on the render thread
  35. GLsync present_fence{}; /// Fence created on the presentation thread
  36. bool is_srgb{}; /// Framebuffer is sRGB or RGB
  37. };
  38. /**
  39. * For smooth Vsync rendering, we want to always present the latest frame that the core generates,
  40. * but also make sure that rendering happens at the pace that the frontend dictates. This is a
  41. * helper class that the renderer uses to sync frames between the render thread and the presentation
  42. * thread
  43. */
  44. class FrameMailbox {
  45. public:
  46. std::mutex swap_chain_lock;
  47. std::condition_variable present_cv;
  48. std::array<Frame, SWAP_CHAIN_SIZE> swap_chain{};
  49. std::queue<Frame*> free_queue;
  50. std::deque<Frame*> present_queue;
  51. Frame* previous_frame{};
  52. FrameMailbox() {
  53. for (auto& frame : swap_chain) {
  54. free_queue.push(&frame);
  55. }
  56. }
  57. ~FrameMailbox() {
  58. // lock the mutex and clear out the present and free_queues and notify any people who are
  59. // blocked to prevent deadlock on shutdown
  60. std::scoped_lock lock{swap_chain_lock};
  61. std::queue<Frame*>().swap(free_queue);
  62. present_queue.clear();
  63. present_cv.notify_all();
  64. }
  65. void ReloadPresentFrame(Frame* frame, u32 height, u32 width) {
  66. frame->present.Release();
  67. frame->present.Create();
  68. GLint previous_draw_fbo{};
  69. glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &previous_draw_fbo);
  70. glBindFramebuffer(GL_FRAMEBUFFER, frame->present.handle);
  71. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER,
  72. frame->color.handle);
  73. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
  74. LOG_CRITICAL(Render_OpenGL, "Failed to recreate present FBO!");
  75. }
  76. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, previous_draw_fbo);
  77. frame->color_reloaded = false;
  78. }
  79. void ReloadRenderFrame(Frame* frame, u32 width, u32 height) {
  80. // Recreate the color texture attachment
  81. frame->color.Release();
  82. frame->color.Create();
  83. const GLenum internal_format = frame->is_srgb ? GL_SRGB8 : GL_RGB8;
  84. glNamedRenderbufferStorage(frame->color.handle, internal_format, width, height);
  85. // Recreate the FBO for the render target
  86. frame->render.Release();
  87. frame->render.Create();
  88. glBindFramebuffer(GL_FRAMEBUFFER, frame->render.handle);
  89. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER,
  90. frame->color.handle);
  91. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
  92. LOG_CRITICAL(Render_OpenGL, "Failed to recreate render FBO!");
  93. }
  94. frame->width = width;
  95. frame->height = height;
  96. frame->color_reloaded = true;
  97. }
  98. Frame* GetRenderFrame() {
  99. std::unique_lock lock{swap_chain_lock};
  100. // If theres no free frames, we will reuse the oldest render frame
  101. if (free_queue.empty()) {
  102. auto frame = present_queue.back();
  103. present_queue.pop_back();
  104. return frame;
  105. }
  106. Frame* frame = free_queue.front();
  107. free_queue.pop();
  108. return frame;
  109. }
  110. void ReleaseRenderFrame(Frame* frame) {
  111. std::unique_lock lock{swap_chain_lock};
  112. present_queue.push_front(frame);
  113. present_cv.notify_one();
  114. }
  115. Frame* TryGetPresentFrame(int timeout_ms) {
  116. std::unique_lock lock{swap_chain_lock};
  117. // wait for new entries in the present_queue
  118. present_cv.wait_for(lock, std::chrono::milliseconds(timeout_ms),
  119. [&] { return !present_queue.empty(); });
  120. if (present_queue.empty()) {
  121. // timed out waiting for a frame to draw so return the previous frame
  122. return previous_frame;
  123. }
  124. // free the previous frame and add it back to the free queue
  125. if (previous_frame) {
  126. free_queue.push(previous_frame);
  127. }
  128. // the newest entries are pushed to the front of the queue
  129. Frame* frame = present_queue.front();
  130. present_queue.pop_front();
  131. // remove all old entries from the present queue and move them back to the free_queue
  132. for (auto f : present_queue) {
  133. free_queue.push(f);
  134. }
  135. present_queue.clear();
  136. previous_frame = frame;
  137. return frame;
  138. }
  139. };
  140. namespace {
  141. constexpr char vertex_shader[] = R"(
  142. #version 430 core
  143. layout (location = 0) in vec2 vert_position;
  144. layout (location = 1) in vec2 vert_tex_coord;
  145. layout (location = 0) out vec2 frag_tex_coord;
  146. // This is a truncated 3x3 matrix for 2D transformations:
  147. // The upper-left 2x2 submatrix performs scaling/rotation/mirroring.
  148. // The third column performs translation.
  149. // The third row could be used for projection, which we don't need in 2D. It hence is assumed to
  150. // implicitly be [0, 0, 1]
  151. layout (location = 0) uniform mat3x2 modelview_matrix;
  152. void main() {
  153. // Multiply input position by the rotscale part of the matrix and then manually translate by
  154. // the last column. This is equivalent to using a full 3x3 matrix and expanding the vector
  155. // to `vec3(vert_position.xy, 1.0)`
  156. gl_Position = vec4(mat2(modelview_matrix) * vert_position + modelview_matrix[2], 0.0, 1.0);
  157. frag_tex_coord = vert_tex_coord;
  158. }
  159. )";
  160. constexpr char fragment_shader[] = R"(
  161. #version 430 core
  162. layout (location = 0) in vec2 frag_tex_coord;
  163. layout (location = 0) out vec4 color;
  164. layout (binding = 0) uniform sampler2D color_texture;
  165. void main() {
  166. color = texture(color_texture, frag_tex_coord);
  167. }
  168. )";
  169. constexpr GLint PositionLocation = 0;
  170. constexpr GLint TexCoordLocation = 1;
  171. constexpr GLint ModelViewMatrixLocation = 0;
  172. struct ScreenRectVertex {
  173. constexpr ScreenRectVertex(u32 x, u32 y, GLfloat u, GLfloat v)
  174. : position{{static_cast<GLfloat>(x), static_cast<GLfloat>(y)}}, tex_coord{{u, v}} {}
  175. std::array<GLfloat, 2> position;
  176. std::array<GLfloat, 2> tex_coord;
  177. };
  178. /**
  179. * Defines a 1:1 pixel ortographic projection matrix with (0,0) on the top-left
  180. * corner and (width, height) on the lower-bottom.
  181. *
  182. * The projection part of the matrix is trivial, hence these operations are represented
  183. * by a 3x2 matrix.
  184. */
  185. std::array<GLfloat, 3 * 2> MakeOrthographicMatrix(float width, float height) {
  186. std::array<GLfloat, 3 * 2> matrix; // Laid out in column-major order
  187. // clang-format off
  188. matrix[0] = 2.f / width; matrix[2] = 0.f; matrix[4] = -1.f;
  189. matrix[1] = 0.f; matrix[3] = -2.f / height; matrix[5] = 1.f;
  190. // Last matrix row is implicitly assumed to be [0, 0, 1].
  191. // clang-format on
  192. return matrix;
  193. }
  194. const char* GetSource(GLenum source) {
  195. switch (source) {
  196. case GL_DEBUG_SOURCE_API:
  197. return "API";
  198. case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
  199. return "WINDOW_SYSTEM";
  200. case GL_DEBUG_SOURCE_SHADER_COMPILER:
  201. return "SHADER_COMPILER";
  202. case GL_DEBUG_SOURCE_THIRD_PARTY:
  203. return "THIRD_PARTY";
  204. case GL_DEBUG_SOURCE_APPLICATION:
  205. return "APPLICATION";
  206. case GL_DEBUG_SOURCE_OTHER:
  207. return "OTHER";
  208. default:
  209. UNREACHABLE();
  210. return "Unknown source";
  211. }
  212. }
  213. const char* GetType(GLenum type) {
  214. switch (type) {
  215. case GL_DEBUG_TYPE_ERROR:
  216. return "ERROR";
  217. case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
  218. return "DEPRECATED_BEHAVIOR";
  219. case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
  220. return "UNDEFINED_BEHAVIOR";
  221. case GL_DEBUG_TYPE_PORTABILITY:
  222. return "PORTABILITY";
  223. case GL_DEBUG_TYPE_PERFORMANCE:
  224. return "PERFORMANCE";
  225. case GL_DEBUG_TYPE_OTHER:
  226. return "OTHER";
  227. case GL_DEBUG_TYPE_MARKER:
  228. return "MARKER";
  229. default:
  230. UNREACHABLE();
  231. return "Unknown type";
  232. }
  233. }
  234. void APIENTRY DebugHandler(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
  235. const GLchar* message, const void* user_param) {
  236. const char format[] = "{} {} {}: {}";
  237. const char* const str_source = GetSource(source);
  238. const char* const str_type = GetType(type);
  239. switch (severity) {
  240. case GL_DEBUG_SEVERITY_HIGH:
  241. LOG_CRITICAL(Render_OpenGL, format, str_source, str_type, id, message);
  242. break;
  243. case GL_DEBUG_SEVERITY_MEDIUM:
  244. LOG_WARNING(Render_OpenGL, format, str_source, str_type, id, message);
  245. break;
  246. case GL_DEBUG_SEVERITY_NOTIFICATION:
  247. case GL_DEBUG_SEVERITY_LOW:
  248. LOG_DEBUG(Render_OpenGL, format, str_source, str_type, id, message);
  249. break;
  250. }
  251. }
  252. } // Anonymous namespace
  253. RendererOpenGL::RendererOpenGL(Core::Frontend::EmuWindow& emu_window, Core::System& system)
  254. : VideoCore::RendererBase{emu_window}, emu_window{emu_window}, system{system},
  255. frame_mailbox{std::make_unique<FrameMailbox>()} {}
  256. RendererOpenGL::~RendererOpenGL() = default;
  257. MICROPROFILE_DEFINE(OpenGL_RenderFrame, "OpenGL", "Render Frame", MP_RGB(128, 128, 64));
  258. MICROPROFILE_DEFINE(OpenGL_WaitPresent, "OpenGL", "Wait For Present", MP_RGB(128, 128, 128));
  259. void RendererOpenGL::SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
  260. render_window.PollEvents();
  261. if (!framebuffer) {
  262. return;
  263. }
  264. PrepareRendertarget(framebuffer);
  265. RenderScreenshot();
  266. Frame* frame;
  267. {
  268. MICROPROFILE_SCOPE(OpenGL_WaitPresent);
  269. frame = frame_mailbox->GetRenderFrame();
  270. // Clean up sync objects before drawing
  271. // INTEL driver workaround. We can't delete the previous render sync object until we are
  272. // sure that the presentation is done
  273. if (frame->present_fence) {
  274. glClientWaitSync(frame->present_fence, 0, GL_TIMEOUT_IGNORED);
  275. }
  276. // delete the draw fence if the frame wasn't presented
  277. if (frame->render_fence) {
  278. glDeleteSync(frame->render_fence);
  279. frame->render_fence = 0;
  280. }
  281. // wait for the presentation to be done
  282. if (frame->present_fence) {
  283. glWaitSync(frame->present_fence, 0, GL_TIMEOUT_IGNORED);
  284. glDeleteSync(frame->present_fence);
  285. frame->present_fence = 0;
  286. }
  287. }
  288. {
  289. MICROPROFILE_SCOPE(OpenGL_RenderFrame);
  290. const auto& layout = render_window.GetFramebufferLayout();
  291. // Recreate the frame if the size of the window has changed
  292. if (layout.width != frame->width || layout.height != frame->height ||
  293. screen_info.display_srgb != frame->is_srgb) {
  294. LOG_DEBUG(Render_OpenGL, "Reloading render frame");
  295. frame->is_srgb = screen_info.display_srgb;
  296. frame_mailbox->ReloadRenderFrame(frame, layout.width, layout.height);
  297. }
  298. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frame->render.handle);
  299. DrawScreen(layout);
  300. // Create a fence for the frontend to wait on and swap this frame to OffTex
  301. frame->render_fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
  302. glFlush();
  303. frame_mailbox->ReleaseRenderFrame(frame);
  304. m_current_frame++;
  305. rasterizer->TickFrame();
  306. }
  307. }
  308. void RendererOpenGL::PrepareRendertarget(const Tegra::FramebufferConfig* framebuffer) {
  309. if (framebuffer) {
  310. // If framebuffer is provided, reload it from memory to a texture
  311. if (screen_info.texture.width != static_cast<GLsizei>(framebuffer->width) ||
  312. screen_info.texture.height != static_cast<GLsizei>(framebuffer->height) ||
  313. screen_info.texture.pixel_format != framebuffer->pixel_format ||
  314. gl_framebuffer_data.empty()) {
  315. // Reallocate texture if the framebuffer size has changed.
  316. // This is expected to not happen very often and hence should not be a
  317. // performance problem.
  318. ConfigureFramebufferTexture(screen_info.texture, *framebuffer);
  319. }
  320. // Load the framebuffer from memory, draw it to the screen, and swap buffers
  321. LoadFBToScreenInfo(*framebuffer);
  322. }
  323. }
  324. void RendererOpenGL::LoadFBToScreenInfo(const Tegra::FramebufferConfig& framebuffer) {
  325. // Framebuffer orientation handling
  326. framebuffer_transform_flags = framebuffer.transform_flags;
  327. framebuffer_crop_rect = framebuffer.crop_rect;
  328. const VAddr framebuffer_addr{framebuffer.address + framebuffer.offset};
  329. if (rasterizer->AccelerateDisplay(framebuffer, framebuffer_addr, framebuffer.stride)) {
  330. return;
  331. }
  332. // Reset the screen info's display texture to its own permanent texture
  333. screen_info.display_texture = screen_info.texture.resource.handle;
  334. const auto pixel_format{
  335. VideoCore::Surface::PixelFormatFromGPUPixelFormat(framebuffer.pixel_format)};
  336. const u32 bytes_per_pixel{VideoCore::Surface::GetBytesPerPixel(pixel_format)};
  337. const u64 size_in_bytes{framebuffer.stride * framebuffer.height * bytes_per_pixel};
  338. u8* const host_ptr{system.Memory().GetPointer(framebuffer_addr)};
  339. rasterizer->FlushRegion(ToCacheAddr(host_ptr), size_in_bytes);
  340. // TODO(Rodrigo): Read this from HLE
  341. constexpr u32 block_height_log2 = 4;
  342. VideoCore::MortonSwizzle(VideoCore::MortonSwizzleMode::MortonToLinear, pixel_format,
  343. framebuffer.stride, block_height_log2, framebuffer.height, 0, 1, 1,
  344. gl_framebuffer_data.data(), host_ptr);
  345. glPixelStorei(GL_UNPACK_ROW_LENGTH, static_cast<GLint>(framebuffer.stride));
  346. // Update existing texture
  347. // TODO: Test what happens on hardware when you change the framebuffer dimensions so that
  348. // they differ from the LCD resolution.
  349. // TODO: Applications could theoretically crash yuzu here by specifying too large
  350. // framebuffer sizes. We should make sure that this cannot happen.
  351. glTextureSubImage2D(screen_info.texture.resource.handle, 0, 0, 0, framebuffer.width,
  352. framebuffer.height, screen_info.texture.gl_format,
  353. screen_info.texture.gl_type, gl_framebuffer_data.data());
  354. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  355. }
  356. void RendererOpenGL::LoadColorToActiveGLTexture(u8 color_r, u8 color_g, u8 color_b, u8 color_a,
  357. const TextureInfo& texture) {
  358. const u8 framebuffer_data[4] = {color_a, color_b, color_g, color_r};
  359. glClearTexImage(texture.resource.handle, 0, GL_RGBA, GL_UNSIGNED_BYTE, framebuffer_data);
  360. }
  361. void RendererOpenGL::InitOpenGLObjects() {
  362. glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue,
  363. 0.0f);
  364. // Link shaders and get variable locations
  365. shader.CreateFromSource(vertex_shader, nullptr, fragment_shader);
  366. state.draw.shader_program = shader.handle;
  367. state.Apply();
  368. // Generate VBO handle for drawing
  369. vertex_buffer.Create();
  370. // Attach vertex data to VAO
  371. glNamedBufferData(vertex_buffer.handle, sizeof(ScreenRectVertex) * 4, nullptr, GL_STREAM_DRAW);
  372. // Allocate textures for the screen
  373. screen_info.texture.resource.Create(GL_TEXTURE_2D);
  374. const GLuint texture = screen_info.texture.resource.handle;
  375. glTextureStorage2D(texture, 1, GL_RGBA8, 1, 1);
  376. screen_info.display_texture = screen_info.texture.resource.handle;
  377. // Clear screen to black
  378. LoadColorToActiveGLTexture(0, 0, 0, 0, screen_info.texture);
  379. }
  380. void RendererOpenGL::AddTelemetryFields() {
  381. const char* const gl_version{reinterpret_cast<char const*>(glGetString(GL_VERSION))};
  382. const char* const gpu_vendor{reinterpret_cast<char const*>(glGetString(GL_VENDOR))};
  383. const char* const gpu_model{reinterpret_cast<char const*>(glGetString(GL_RENDERER))};
  384. LOG_INFO(Render_OpenGL, "GL_VERSION: {}", gl_version);
  385. LOG_INFO(Render_OpenGL, "GL_VENDOR: {}", gpu_vendor);
  386. LOG_INFO(Render_OpenGL, "GL_RENDERER: {}", gpu_model);
  387. auto& telemetry_session = system.TelemetrySession();
  388. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_Vendor", gpu_vendor);
  389. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_Model", gpu_model);
  390. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_OpenGL_Version", gl_version);
  391. }
  392. void RendererOpenGL::CreateRasterizer() {
  393. if (rasterizer) {
  394. return;
  395. }
  396. rasterizer = std::make_unique<RasterizerOpenGL>(system, emu_window, screen_info);
  397. }
  398. void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
  399. const Tegra::FramebufferConfig& framebuffer) {
  400. texture.width = framebuffer.width;
  401. texture.height = framebuffer.height;
  402. texture.pixel_format = framebuffer.pixel_format;
  403. const auto pixel_format{
  404. VideoCore::Surface::PixelFormatFromGPUPixelFormat(framebuffer.pixel_format)};
  405. const u32 bytes_per_pixel{VideoCore::Surface::GetBytesPerPixel(pixel_format)};
  406. gl_framebuffer_data.resize(texture.width * texture.height * bytes_per_pixel);
  407. GLint internal_format;
  408. switch (framebuffer.pixel_format) {
  409. case Tegra::FramebufferConfig::PixelFormat::ABGR8:
  410. internal_format = GL_RGBA8;
  411. texture.gl_format = GL_RGBA;
  412. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV;
  413. break;
  414. case Tegra::FramebufferConfig::PixelFormat::RGB565:
  415. internal_format = GL_RGB565;
  416. texture.gl_format = GL_RGB;
  417. texture.gl_type = GL_UNSIGNED_SHORT_5_6_5;
  418. break;
  419. default:
  420. internal_format = GL_RGBA8;
  421. texture.gl_format = GL_RGBA;
  422. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV;
  423. UNIMPLEMENTED_MSG("Unknown framebuffer pixel format: {}",
  424. static_cast<u32>(framebuffer.pixel_format));
  425. }
  426. texture.resource.Release();
  427. texture.resource.Create(GL_TEXTURE_2D);
  428. glTextureStorage2D(texture.resource.handle, 1, internal_format, texture.width, texture.height);
  429. }
  430. void RendererOpenGL::DrawScreen(const Layout::FramebufferLayout& layout) {
  431. if (renderer_settings.set_background_color) {
  432. // Update background color before drawing
  433. glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue,
  434. 0.0f);
  435. }
  436. // Set projection matrix
  437. const std::array ortho_matrix =
  438. MakeOrthographicMatrix(static_cast<float>(layout.width), static_cast<float>(layout.height));
  439. glUniformMatrix3x2fv(ModelViewMatrixLocation, 1, GL_FALSE, ortho_matrix.data());
  440. const auto& texcoords = screen_info.display_texcoords;
  441. auto left = texcoords.left;
  442. auto right = texcoords.right;
  443. if (framebuffer_transform_flags != Tegra::FramebufferConfig::TransformFlags::Unset) {
  444. if (framebuffer_transform_flags == Tegra::FramebufferConfig::TransformFlags::FlipV) {
  445. // Flip the framebuffer vertically
  446. left = texcoords.right;
  447. right = texcoords.left;
  448. } else {
  449. // Other transformations are unsupported
  450. LOG_CRITICAL(Render_OpenGL, "Unsupported framebuffer_transform_flags={}",
  451. static_cast<u32>(framebuffer_transform_flags));
  452. UNIMPLEMENTED();
  453. }
  454. }
  455. ASSERT_MSG(framebuffer_crop_rect.top == 0, "Unimplemented");
  456. ASSERT_MSG(framebuffer_crop_rect.left == 0, "Unimplemented");
  457. // Scale the output by the crop width/height. This is commonly used with 1280x720 rendering
  458. // (e.g. handheld mode) on a 1920x1080 framebuffer.
  459. f32 scale_u = 1.f, scale_v = 1.f;
  460. if (framebuffer_crop_rect.GetWidth() > 0) {
  461. scale_u = static_cast<f32>(framebuffer_crop_rect.GetWidth()) /
  462. static_cast<f32>(screen_info.texture.width);
  463. }
  464. if (framebuffer_crop_rect.GetHeight() > 0) {
  465. scale_v = static_cast<f32>(framebuffer_crop_rect.GetHeight()) /
  466. static_cast<f32>(screen_info.texture.height);
  467. }
  468. const auto& screen = layout.screen;
  469. const std::array vertices = {
  470. ScreenRectVertex(screen.left, screen.top, texcoords.top * scale_u, left * scale_v),
  471. ScreenRectVertex(screen.right, screen.top, texcoords.bottom * scale_u, left * scale_v),
  472. ScreenRectVertex(screen.left, screen.bottom, texcoords.top * scale_u, right * scale_v),
  473. ScreenRectVertex(screen.right, screen.bottom, texcoords.bottom * scale_u, right * scale_v),
  474. };
  475. glNamedBufferSubData(vertex_buffer.handle, 0, sizeof(vertices), std::data(vertices));
  476. state.Apply();
  477. // TODO: Signal state tracker about these changes
  478. glEnable(GL_CULL_FACE);
  479. if (screen_info.display_srgb) {
  480. glEnable(GL_FRAMEBUFFER_SRGB);
  481. } else {
  482. glDisable(GL_FRAMEBUFFER_SRGB);
  483. }
  484. glDisable(GL_COLOR_LOGIC_OP);
  485. glDisable(GL_ALPHA_TEST);
  486. glDisable(GL_DEPTH_TEST);
  487. glDisable(GL_STENCIL_TEST);
  488. glDisable(GL_POLYGON_OFFSET_FILL);
  489. glDisable(GL_RASTERIZER_DISCARD);
  490. glDisablei(GL_BLEND, 0);
  491. glDisablei(GL_SCISSOR_TEST, 0);
  492. glCullFace(GL_BACK);
  493. glFrontFace(GL_CW);
  494. glColorMaski(0, GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  495. glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE);
  496. glViewport(0, 0, layout.width, layout.height);
  497. glVertexAttribFormat(PositionLocation, 2, GL_FLOAT, GL_FALSE,
  498. offsetof(ScreenRectVertex, position));
  499. glVertexAttribFormat(TexCoordLocation, 2, GL_FLOAT, GL_FALSE,
  500. offsetof(ScreenRectVertex, tex_coord));
  501. glVertexAttribBinding(PositionLocation, 0);
  502. glVertexAttribBinding(TexCoordLocation, 0);
  503. glBindVertexBuffer(0, vertex_buffer.handle, 0, sizeof(ScreenRectVertex));
  504. glBindTextureUnit(0, screen_info.display_texture);
  505. glBindSampler(0, 0);
  506. glClear(GL_COLOR_BUFFER_BIT);
  507. glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  508. // Restore default state
  509. state.Apply();
  510. }
  511. void RendererOpenGL::TryPresent(int timeout_ms) {
  512. const auto& layout = render_window.GetFramebufferLayout();
  513. auto frame = frame_mailbox->TryGetPresentFrame(timeout_ms);
  514. if (!frame) {
  515. LOG_DEBUG(Render_OpenGL, "TryGetPresentFrame returned no frame to present");
  516. return;
  517. }
  518. // Clearing before a full overwrite of a fbo can signal to drivers that they can avoid a
  519. // readback since we won't be doing any blending
  520. glClear(GL_COLOR_BUFFER_BIT);
  521. // Recreate the presentation FBO if the color attachment was changed
  522. if (frame->color_reloaded) {
  523. LOG_DEBUG(Render_OpenGL, "Reloading present frame");
  524. frame_mailbox->ReloadPresentFrame(frame, layout.width, layout.height);
  525. }
  526. glWaitSync(frame->render_fence, 0, GL_TIMEOUT_IGNORED);
  527. // INTEL workaround.
  528. // Normally we could just delete the draw fence here, but due to driver bugs, we can just delete
  529. // it on the emulation thread without too much penalty
  530. // glDeleteSync(frame.render_sync);
  531. // frame.render_sync = 0;
  532. glBindFramebuffer(GL_READ_FRAMEBUFFER, frame->present.handle);
  533. glBlitFramebuffer(0, 0, frame->width, frame->height, 0, 0, layout.width, layout.height,
  534. GL_COLOR_BUFFER_BIT, GL_LINEAR);
  535. // Insert fence for the main thread to block on
  536. frame->present_fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
  537. glFlush();
  538. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  539. }
  540. void RendererOpenGL::RenderScreenshot() {
  541. if (!renderer_settings.screenshot_requested) {
  542. return;
  543. }
  544. GLint old_read_fb;
  545. GLint old_draw_fb;
  546. glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &old_read_fb);
  547. glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &old_draw_fb);
  548. // Draw the current frame to the screenshot framebuffer
  549. screenshot_framebuffer.Create();
  550. glBindFramebuffer(GL_FRAMEBUFFER, screenshot_framebuffer.handle);
  551. Layout::FramebufferLayout layout{renderer_settings.screenshot_framebuffer_layout};
  552. GLuint renderbuffer;
  553. glGenRenderbuffers(1, &renderbuffer);
  554. glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
  555. glRenderbufferStorage(GL_RENDERBUFFER, screen_info.display_srgb ? GL_SRGB8 : GL_RGB8,
  556. layout.width, layout.height);
  557. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
  558. DrawScreen(layout);
  559. glReadPixels(0, 0, layout.width, layout.height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV,
  560. renderer_settings.screenshot_bits);
  561. screenshot_framebuffer.Release();
  562. glDeleteRenderbuffers(1, &renderbuffer);
  563. glBindFramebuffer(GL_READ_FRAMEBUFFER, old_read_fb);
  564. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, old_draw_fb);
  565. renderer_settings.screenshot_complete_callback();
  566. renderer_settings.screenshot_requested = false;
  567. }
  568. bool RendererOpenGL::Init() {
  569. if (GLAD_GL_KHR_debug) {
  570. glEnable(GL_DEBUG_OUTPUT);
  571. glDebugMessageCallback(DebugHandler, nullptr);
  572. }
  573. AddTelemetryFields();
  574. if (!GLAD_GL_VERSION_4_3) {
  575. return false;
  576. }
  577. InitOpenGLObjects();
  578. CreateRasterizer();
  579. return true;
  580. }
  581. void RendererOpenGL::ShutDown() {}
  582. } // namespace OpenGL