renderer_opengl.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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/telemetry.h"
  12. #include "core/core.h"
  13. #include "core/core_timing.h"
  14. #include "core/frontend/emu_window.h"
  15. #include "core/frontend/scope_acquire_window_context.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. static const char vertex_shader[] = R"(
  25. #version 150 core
  26. in vec2 vert_position;
  27. in vec2 vert_tex_coord;
  28. out vec2 frag_tex_coord;
  29. // This is a truncated 3x3 matrix for 2D transformations:
  30. // The upper-left 2x2 submatrix performs scaling/rotation/mirroring.
  31. // The third column performs translation.
  32. // The third row could be used for projection, which we don't need in 2D. It hence is assumed to
  33. // implicitly be [0, 0, 1]
  34. uniform mat3x2 modelview_matrix;
  35. void main() {
  36. // Multiply input position by the rotscale part of the matrix and then manually translate by
  37. // the last column. This is equivalent to using a full 3x3 matrix and expanding the vector
  38. // to `vec3(vert_position.xy, 1.0)`
  39. gl_Position = vec4(mat2(modelview_matrix) * vert_position + modelview_matrix[2], 0.0, 1.0);
  40. frag_tex_coord = vert_tex_coord;
  41. }
  42. )";
  43. static const char fragment_shader[] = R"(
  44. #version 150 core
  45. in vec2 frag_tex_coord;
  46. out vec4 color;
  47. uniform sampler2D color_texture;
  48. void main() {
  49. // Swap RGBA -> ABGR so we don't have to do this on the CPU. This needs to change if we have to
  50. // support more framebuffer pixel formats.
  51. color = texture(color_texture, frag_tex_coord);
  52. }
  53. )";
  54. /// Vertex structure that the drawn screen rectangles are composed of.
  55. struct ScreenRectVertex {
  56. ScreenRectVertex(GLfloat x, GLfloat y, GLfloat u, GLfloat v) {
  57. position[0] = x;
  58. position[1] = y;
  59. tex_coord[0] = u;
  60. tex_coord[1] = v;
  61. }
  62. GLfloat position[2];
  63. GLfloat tex_coord[2];
  64. };
  65. /**
  66. * Defines a 1:1 pixel ortographic projection matrix with (0,0) on the top-left
  67. * corner and (width, height) on the lower-bottom.
  68. *
  69. * The projection part of the matrix is trivial, hence these operations are represented
  70. * by a 3x2 matrix.
  71. */
  72. static std::array<GLfloat, 3 * 2> MakeOrthographicMatrix(const float width, const float height) {
  73. std::array<GLfloat, 3 * 2> matrix; // Laid out in column-major order
  74. // clang-format off
  75. matrix[0] = 2.f / width; matrix[2] = 0.f; matrix[4] = -1.f;
  76. matrix[1] = 0.f; matrix[3] = -2.f / height; matrix[5] = 1.f;
  77. // Last matrix row is implicitly assumed to be [0, 0, 1].
  78. // clang-format on
  79. return matrix;
  80. }
  81. RendererOpenGL::RendererOpenGL(Core::Frontend::EmuWindow& emu_window, Core::System& system)
  82. : VideoCore::RendererBase{emu_window}, emu_window{emu_window}, system{system} {}
  83. RendererOpenGL::~RendererOpenGL() = default;
  84. void RendererOpenGL::SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
  85. // Maintain the rasterizer's state as a priority
  86. OpenGLState prev_state = OpenGLState::GetCurState();
  87. state.AllDirty();
  88. state.Apply();
  89. if (framebuffer) {
  90. // If framebuffer is provided, reload it from memory to a texture
  91. if (screen_info.texture.width != static_cast<GLsizei>(framebuffer->width) ||
  92. screen_info.texture.height != static_cast<GLsizei>(framebuffer->height) ||
  93. screen_info.texture.pixel_format != framebuffer->pixel_format) {
  94. // Reallocate texture if the framebuffer size has changed.
  95. // This is expected to not happen very often and hence should not be a
  96. // performance problem.
  97. ConfigureFramebufferTexture(screen_info.texture, *framebuffer);
  98. }
  99. // Load the framebuffer from memory, draw it to the screen, and swap buffers
  100. LoadFBToScreenInfo(*framebuffer);
  101. if (renderer_settings.screenshot_requested)
  102. CaptureScreenshot();
  103. DrawScreen(render_window.GetFramebufferLayout());
  104. rasterizer->TickFrame();
  105. render_window.SwapBuffers();
  106. }
  107. render_window.PollEvents();
  108. // Restore the rasterizer state
  109. prev_state.AllDirty();
  110. prev_state.Apply();
  111. }
  112. void RendererOpenGL::LoadFBToScreenInfo(const Tegra::FramebufferConfig& framebuffer) {
  113. // Framebuffer orientation handling
  114. framebuffer_transform_flags = framebuffer.transform_flags;
  115. framebuffer_crop_rect = framebuffer.crop_rect;
  116. const VAddr framebuffer_addr{framebuffer.address + framebuffer.offset};
  117. if (rasterizer->AccelerateDisplay(framebuffer, framebuffer_addr, framebuffer.stride)) {
  118. return;
  119. }
  120. // Reset the screen info's display texture to its own permanent texture
  121. screen_info.display_texture = screen_info.texture.resource.handle;
  122. const auto pixel_format{
  123. VideoCore::Surface::PixelFormatFromGPUPixelFormat(framebuffer.pixel_format)};
  124. const u32 bytes_per_pixel{VideoCore::Surface::GetBytesPerPixel(pixel_format)};
  125. const u64 size_in_bytes{framebuffer.stride * framebuffer.height * bytes_per_pixel};
  126. u8* const host_ptr{system.Memory().GetPointer(framebuffer_addr)};
  127. rasterizer->FlushRegion(ToCacheAddr(host_ptr), size_in_bytes);
  128. // TODO(Rodrigo): Read this from HLE
  129. constexpr u32 block_height_log2 = 4;
  130. VideoCore::MortonSwizzle(VideoCore::MortonSwizzleMode::MortonToLinear, pixel_format,
  131. framebuffer.stride, block_height_log2, framebuffer.height, 0, 1, 1,
  132. gl_framebuffer_data.data(), host_ptr);
  133. glPixelStorei(GL_UNPACK_ROW_LENGTH, static_cast<GLint>(framebuffer.stride));
  134. // Update existing texture
  135. // TODO: Test what happens on hardware when you change the framebuffer dimensions so that
  136. // they differ from the LCD resolution.
  137. // TODO: Applications could theoretically crash yuzu here by specifying too large
  138. // framebuffer sizes. We should make sure that this cannot happen.
  139. glTextureSubImage2D(screen_info.texture.resource.handle, 0, 0, 0, framebuffer.width,
  140. framebuffer.height, screen_info.texture.gl_format,
  141. screen_info.texture.gl_type, gl_framebuffer_data.data());
  142. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  143. }
  144. void RendererOpenGL::LoadColorToActiveGLTexture(u8 color_r, u8 color_g, u8 color_b, u8 color_a,
  145. const TextureInfo& texture) {
  146. const u8 framebuffer_data[4] = {color_a, color_b, color_g, color_r};
  147. glClearTexImage(texture.resource.handle, 0, GL_RGBA, GL_UNSIGNED_BYTE, framebuffer_data);
  148. }
  149. void RendererOpenGL::InitOpenGLObjects() {
  150. glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue,
  151. 0.0f);
  152. // Link shaders and get variable locations
  153. shader.CreateFromSource(vertex_shader, nullptr, fragment_shader);
  154. state.draw.shader_program = shader.handle;
  155. state.AllDirty();
  156. state.Apply();
  157. uniform_modelview_matrix = glGetUniformLocation(shader.handle, "modelview_matrix");
  158. uniform_color_texture = glGetUniformLocation(shader.handle, "color_texture");
  159. attrib_position = glGetAttribLocation(shader.handle, "vert_position");
  160. attrib_tex_coord = glGetAttribLocation(shader.handle, "vert_tex_coord");
  161. // Generate VBO handle for drawing
  162. vertex_buffer.Create();
  163. // Generate VAO
  164. vertex_array.Create();
  165. state.draw.vertex_array = vertex_array.handle;
  166. // Attach vertex data to VAO
  167. glNamedBufferData(vertex_buffer.handle, sizeof(ScreenRectVertex) * 4, nullptr, GL_STREAM_DRAW);
  168. glVertexArrayAttribFormat(vertex_array.handle, attrib_position, 2, GL_FLOAT, GL_FALSE,
  169. offsetof(ScreenRectVertex, position));
  170. glVertexArrayAttribFormat(vertex_array.handle, attrib_tex_coord, 2, GL_FLOAT, GL_FALSE,
  171. offsetof(ScreenRectVertex, tex_coord));
  172. glVertexArrayAttribBinding(vertex_array.handle, attrib_position, 0);
  173. glVertexArrayAttribBinding(vertex_array.handle, attrib_tex_coord, 0);
  174. glEnableVertexArrayAttrib(vertex_array.handle, attrib_position);
  175. glEnableVertexArrayAttrib(vertex_array.handle, attrib_tex_coord);
  176. glVertexArrayVertexBuffer(vertex_array.handle, 0, vertex_buffer.handle, 0,
  177. sizeof(ScreenRectVertex));
  178. // Allocate textures for the screen
  179. screen_info.texture.resource.Create(GL_TEXTURE_2D);
  180. const GLuint texture = screen_info.texture.resource.handle;
  181. glTextureStorage2D(texture, 1, GL_RGBA8, 1, 1);
  182. screen_info.display_texture = screen_info.texture.resource.handle;
  183. // Clear screen to black
  184. LoadColorToActiveGLTexture(0, 0, 0, 0, screen_info.texture);
  185. }
  186. void RendererOpenGL::AddTelemetryFields() {
  187. const char* const gl_version{reinterpret_cast<char const*>(glGetString(GL_VERSION))};
  188. const char* const gpu_vendor{reinterpret_cast<char const*>(glGetString(GL_VENDOR))};
  189. const char* const gpu_model{reinterpret_cast<char const*>(glGetString(GL_RENDERER))};
  190. LOG_INFO(Render_OpenGL, "GL_VERSION: {}", gl_version);
  191. LOG_INFO(Render_OpenGL, "GL_VENDOR: {}", gpu_vendor);
  192. LOG_INFO(Render_OpenGL, "GL_RENDERER: {}", gpu_model);
  193. auto& telemetry_session = system.TelemetrySession();
  194. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_Vendor", gpu_vendor);
  195. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_Model", gpu_model);
  196. telemetry_session.AddField(Telemetry::FieldType::UserSystem, "GPU_OpenGL_Version", gl_version);
  197. }
  198. void RendererOpenGL::CreateRasterizer() {
  199. if (rasterizer) {
  200. return;
  201. }
  202. rasterizer = std::make_unique<RasterizerOpenGL>(system, emu_window, screen_info);
  203. }
  204. void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
  205. const Tegra::FramebufferConfig& framebuffer) {
  206. texture.width = framebuffer.width;
  207. texture.height = framebuffer.height;
  208. texture.pixel_format = framebuffer.pixel_format;
  209. const auto pixel_format{
  210. VideoCore::Surface::PixelFormatFromGPUPixelFormat(framebuffer.pixel_format)};
  211. const u32 bytes_per_pixel{VideoCore::Surface::GetBytesPerPixel(pixel_format)};
  212. gl_framebuffer_data.resize(texture.width * texture.height * bytes_per_pixel);
  213. GLint internal_format;
  214. switch (framebuffer.pixel_format) {
  215. case Tegra::FramebufferConfig::PixelFormat::ABGR8:
  216. internal_format = GL_RGBA8;
  217. texture.gl_format = GL_RGBA;
  218. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV;
  219. break;
  220. case Tegra::FramebufferConfig::PixelFormat::RGB565:
  221. internal_format = GL_RGB565;
  222. texture.gl_format = GL_RGB;
  223. texture.gl_type = GL_UNSIGNED_SHORT_5_6_5;
  224. break;
  225. default:
  226. internal_format = GL_RGBA8;
  227. texture.gl_format = GL_RGBA;
  228. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV;
  229. UNIMPLEMENTED_MSG("Unknown framebuffer pixel format: {}",
  230. static_cast<u32>(framebuffer.pixel_format));
  231. }
  232. texture.resource.Release();
  233. texture.resource.Create(GL_TEXTURE_2D);
  234. glTextureStorage2D(texture.resource.handle, 1, internal_format, texture.width, texture.height);
  235. }
  236. void RendererOpenGL::DrawScreenTriangles(const ScreenInfo& screen_info, float x, float y, float w,
  237. float h) {
  238. const auto& texcoords = screen_info.display_texcoords;
  239. auto left = texcoords.left;
  240. auto right = texcoords.right;
  241. if (framebuffer_transform_flags != Tegra::FramebufferConfig::TransformFlags::Unset) {
  242. if (framebuffer_transform_flags == Tegra::FramebufferConfig::TransformFlags::FlipV) {
  243. // Flip the framebuffer vertically
  244. left = texcoords.right;
  245. right = texcoords.left;
  246. } else {
  247. // Other transformations are unsupported
  248. LOG_CRITICAL(Render_OpenGL, "Unsupported framebuffer_transform_flags={}",
  249. static_cast<u32>(framebuffer_transform_flags));
  250. UNIMPLEMENTED();
  251. }
  252. }
  253. ASSERT_MSG(framebuffer_crop_rect.top == 0, "Unimplemented");
  254. ASSERT_MSG(framebuffer_crop_rect.left == 0, "Unimplemented");
  255. // Scale the output by the crop width/height. This is commonly used with 1280x720 rendering
  256. // (e.g. handheld mode) on a 1920x1080 framebuffer.
  257. f32 scale_u = 1.f, scale_v = 1.f;
  258. if (framebuffer_crop_rect.GetWidth() > 0) {
  259. scale_u = static_cast<f32>(framebuffer_crop_rect.GetWidth()) /
  260. static_cast<f32>(screen_info.texture.width);
  261. }
  262. if (framebuffer_crop_rect.GetHeight() > 0) {
  263. scale_v = static_cast<f32>(framebuffer_crop_rect.GetHeight()) /
  264. static_cast<f32>(screen_info.texture.height);
  265. }
  266. std::array<ScreenRectVertex, 4> vertices = {{
  267. ScreenRectVertex(x, y, texcoords.top * scale_u, left * scale_v),
  268. ScreenRectVertex(x + w, y, texcoords.bottom * scale_u, left * scale_v),
  269. ScreenRectVertex(x, y + h, texcoords.top * scale_u, right * scale_v),
  270. ScreenRectVertex(x + w, y + h, texcoords.bottom * scale_u, right * scale_v),
  271. }};
  272. state.textures[0] = screen_info.display_texture;
  273. state.framebuffer_srgb.enabled = screen_info.display_srgb;
  274. state.AllDirty();
  275. state.Apply();
  276. glNamedBufferSubData(vertex_buffer.handle, 0, sizeof(vertices), vertices.data());
  277. glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  278. // Restore default state
  279. state.framebuffer_srgb.enabled = false;
  280. state.textures[0] = 0;
  281. state.AllDirty();
  282. state.Apply();
  283. }
  284. void RendererOpenGL::DrawScreen(const Layout::FramebufferLayout& layout) {
  285. if (renderer_settings.set_background_color) {
  286. // Update background color before drawing
  287. glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue,
  288. 0.0f);
  289. }
  290. const auto& screen = layout.screen;
  291. glViewport(0, 0, layout.width, layout.height);
  292. glClear(GL_COLOR_BUFFER_BIT);
  293. // Set projection matrix
  294. std::array<GLfloat, 3 * 2> ortho_matrix =
  295. MakeOrthographicMatrix((float)layout.width, (float)layout.height);
  296. glUniformMatrix3x2fv(uniform_modelview_matrix, 1, GL_FALSE, ortho_matrix.data());
  297. // Bind texture in Texture Unit 0
  298. glActiveTexture(GL_TEXTURE0);
  299. glUniform1i(uniform_color_texture, 0);
  300. DrawScreenTriangles(screen_info, (float)screen.left, (float)screen.top,
  301. (float)screen.GetWidth(), (float)screen.GetHeight());
  302. m_current_frame++;
  303. }
  304. void RendererOpenGL::UpdateFramerate() {}
  305. void RendererOpenGL::CaptureScreenshot() {
  306. // Draw the current frame to the screenshot framebuffer
  307. screenshot_framebuffer.Create();
  308. GLuint old_read_fb = state.draw.read_framebuffer;
  309. GLuint old_draw_fb = state.draw.draw_framebuffer;
  310. state.draw.read_framebuffer = state.draw.draw_framebuffer = screenshot_framebuffer.handle;
  311. state.AllDirty();
  312. state.Apply();
  313. Layout::FramebufferLayout layout{renderer_settings.screenshot_framebuffer_layout};
  314. GLuint renderbuffer;
  315. glGenRenderbuffers(1, &renderbuffer);
  316. glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
  317. glRenderbufferStorage(GL_RENDERBUFFER, screen_info.display_srgb ? GL_SRGB8 : GL_RGB8,
  318. layout.width, layout.height);
  319. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
  320. DrawScreen(layout);
  321. glReadPixels(0, 0, layout.width, layout.height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV,
  322. renderer_settings.screenshot_bits);
  323. screenshot_framebuffer.Release();
  324. state.draw.read_framebuffer = old_read_fb;
  325. state.draw.draw_framebuffer = old_draw_fb;
  326. state.AllDirty();
  327. state.Apply();
  328. glDeleteRenderbuffers(1, &renderbuffer);
  329. renderer_settings.screenshot_complete_callback();
  330. renderer_settings.screenshot_requested = false;
  331. }
  332. static const char* GetSource(GLenum source) {
  333. #define RET(s) \
  334. case GL_DEBUG_SOURCE_##s: \
  335. return #s
  336. switch (source) {
  337. RET(API);
  338. RET(WINDOW_SYSTEM);
  339. RET(SHADER_COMPILER);
  340. RET(THIRD_PARTY);
  341. RET(APPLICATION);
  342. RET(OTHER);
  343. default:
  344. UNREACHABLE();
  345. return "Unknown source";
  346. }
  347. #undef RET
  348. }
  349. static const char* GetType(GLenum type) {
  350. #define RET(t) \
  351. case GL_DEBUG_TYPE_##t: \
  352. return #t
  353. switch (type) {
  354. RET(ERROR);
  355. RET(DEPRECATED_BEHAVIOR);
  356. RET(UNDEFINED_BEHAVIOR);
  357. RET(PORTABILITY);
  358. RET(PERFORMANCE);
  359. RET(OTHER);
  360. RET(MARKER);
  361. default:
  362. UNREACHABLE();
  363. return "Unknown type";
  364. }
  365. #undef RET
  366. }
  367. static void APIENTRY DebugHandler(GLenum source, GLenum type, GLuint id, GLenum severity,
  368. GLsizei length, const GLchar* message, const void* user_param) {
  369. const char format[] = "{} {} {}: {}";
  370. const char* const str_source = GetSource(source);
  371. const char* const str_type = GetType(type);
  372. switch (severity) {
  373. case GL_DEBUG_SEVERITY_HIGH:
  374. LOG_CRITICAL(Render_OpenGL, format, str_source, str_type, id, message);
  375. break;
  376. case GL_DEBUG_SEVERITY_MEDIUM:
  377. LOG_WARNING(Render_OpenGL, format, str_source, str_type, id, message);
  378. break;
  379. case GL_DEBUG_SEVERITY_NOTIFICATION:
  380. case GL_DEBUG_SEVERITY_LOW:
  381. LOG_DEBUG(Render_OpenGL, format, str_source, str_type, id, message);
  382. break;
  383. }
  384. }
  385. bool RendererOpenGL::Init() {
  386. Core::Frontend::ScopeAcquireWindowContext acquire_context{render_window};
  387. if (GLAD_GL_KHR_debug) {
  388. glEnable(GL_DEBUG_OUTPUT);
  389. glDebugMessageCallback(DebugHandler, nullptr);
  390. }
  391. AddTelemetryFields();
  392. if (!GLAD_GL_VERSION_4_3) {
  393. return false;
  394. }
  395. InitOpenGLObjects();
  396. CreateRasterizer();
  397. return true;
  398. }
  399. void RendererOpenGL::ShutDown() {}
  400. } // namespace OpenGL