renderer_opengl.cpp 29 KB

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