renderer_opengl.cpp 17 KB

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