renderer_opengl.cpp 16 KB

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