renderer_opengl.cpp 17 KB

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