renderer_opengl.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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 "common/assert.h"
  8. #include "common/emu_window.h"
  9. #include "common/logging/log.h"
  10. #include "common/profiler_reporting.h"
  11. #include "core/memory.h"
  12. #include "core/settings.h"
  13. #include "core/hw/gpu.h"
  14. #include "core/hw/hw.h"
  15. #include "core/hw/lcd.h"
  16. #include "video_core/video_core.h"
  17. #include "video_core/debug_utils/debug_utils.h"
  18. #include "video_core/renderer_opengl/gl_rasterizer.h"
  19. #include "video_core/renderer_opengl/gl_shader_util.h"
  20. #include "video_core/renderer_opengl/renderer_opengl.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. color = texture(color_texture, frag_tex_coord);
  47. }
  48. )";
  49. /**
  50. * Vertex structure that the drawn screen rectangles are composed of.
  51. */
  52. struct ScreenRectVertex {
  53. ScreenRectVertex(GLfloat x, GLfloat y, GLfloat u, GLfloat v) {
  54. position[0] = x;
  55. position[1] = y;
  56. tex_coord[0] = u;
  57. tex_coord[1] = v;
  58. }
  59. GLfloat position[2];
  60. GLfloat tex_coord[2];
  61. };
  62. /**
  63. * Defines a 1:1 pixel ortographic projection matrix with (0,0) on the top-left
  64. * corner and (width, height) on the lower-bottom.
  65. *
  66. * The projection part of the matrix is trivial, hence these operations are represented
  67. * by a 3x2 matrix.
  68. */
  69. static std::array<GLfloat, 3*2> MakeOrthographicMatrix(const float width, const float height) {
  70. std::array<GLfloat, 3*2> matrix;
  71. matrix[0] = 2.f / width; matrix[2] = 0.f; matrix[4] = -1.f;
  72. matrix[1] = 0.f; matrix[3] = -2.f / height; matrix[5] = 1.f;
  73. // Last matrix row is implicitly assumed to be [0, 0, 1].
  74. return matrix;
  75. }
  76. /// RendererOpenGL constructor
  77. RendererOpenGL::RendererOpenGL() {
  78. resolution_width = std::max(VideoCore::kScreenTopWidth, VideoCore::kScreenBottomWidth);
  79. resolution_height = VideoCore::kScreenTopHeight + VideoCore::kScreenBottomHeight;
  80. }
  81. /// RendererOpenGL destructor
  82. RendererOpenGL::~RendererOpenGL() {
  83. }
  84. /// Swap buffers (render frame)
  85. void RendererOpenGL::SwapBuffers() {
  86. // Maintain the rasterizer's state as a priority
  87. OpenGLState prev_state = OpenGLState::GetCurState();
  88. state.Apply();
  89. for(int i : {0, 1}) {
  90. const auto& framebuffer = GPU::g_regs.framebuffer_config[i];
  91. // Main LCD (0): 0x1ED02204, Sub LCD (1): 0x1ED02A04
  92. u32 lcd_color_addr = (i == 0) ? LCD_REG_INDEX(color_fill_top) : LCD_REG_INDEX(color_fill_bottom);
  93. lcd_color_addr = HW::VADDR_LCD + 4 * lcd_color_addr;
  94. LCD::Regs::ColorFill color_fill = {0};
  95. LCD::Read(color_fill.raw, lcd_color_addr);
  96. if (color_fill.is_enabled) {
  97. LoadColorToActiveGLTexture(color_fill.color_r, color_fill.color_g, color_fill.color_b, textures[i]);
  98. // Resize the texture in case the framebuffer size has changed
  99. textures[i].width = 1;
  100. textures[i].height = 1;
  101. } else {
  102. if (textures[i].width != (GLsizei)framebuffer.width ||
  103. textures[i].height != (GLsizei)framebuffer.height ||
  104. textures[i].format != framebuffer.color_format) {
  105. // Reallocate texture if the framebuffer size has changed.
  106. // This is expected to not happen very often and hence should not be a
  107. // performance problem.
  108. ConfigureFramebufferTexture(textures[i], framebuffer);
  109. }
  110. LoadFBToActiveGLTexture(framebuffer, textures[i]);
  111. // Resize the texture in case the framebuffer size has changed
  112. textures[i].width = framebuffer.width;
  113. textures[i].height = framebuffer.height;
  114. }
  115. }
  116. DrawScreens();
  117. auto& profiler = Common::Profiling::GetProfilingManager();
  118. profiler.FinishFrame();
  119. {
  120. auto aggregator = Common::Profiling::GetTimingResultsAggregator();
  121. aggregator->AddFrame(profiler.GetPreviousFrameResults());
  122. }
  123. // Swap buffers
  124. render_window->PollEvents();
  125. render_window->SwapBuffers();
  126. prev_state.Apply();
  127. profiler.BeginFrame();
  128. RefreshRasterizerSetting();
  129. if (Pica::g_debug_context && Pica::g_debug_context->recorder) {
  130. Pica::g_debug_context->recorder->FrameFinished();
  131. }
  132. }
  133. /**
  134. * Loads framebuffer from emulated memory into the active OpenGL texture.
  135. */
  136. void RendererOpenGL::LoadFBToActiveGLTexture(const GPU::Regs::FramebufferConfig& framebuffer,
  137. const TextureInfo& texture) {
  138. const PAddr framebuffer_addr = framebuffer.active_fb == 0 ?
  139. framebuffer.address_left1 : framebuffer.address_left2;
  140. LOG_TRACE(Render_OpenGL, "0x%08x bytes from 0x%08x(%dx%d), fmt %x",
  141. framebuffer.stride * framebuffer.height,
  142. framebuffer_addr, (int)framebuffer.width,
  143. (int)framebuffer.height, (int)framebuffer.format);
  144. const u8* framebuffer_data = Memory::GetPhysicalPointer(framebuffer_addr);
  145. int bpp = GPU::Regs::BytesPerPixel(framebuffer.color_format);
  146. size_t pixel_stride = framebuffer.stride / bpp;
  147. // OpenGL only supports specifying a stride in units of pixels, not bytes, unfortunately
  148. ASSERT(pixel_stride * bpp == framebuffer.stride);
  149. // Ensure no bad interactions with GL_UNPACK_ALIGNMENT, which by default
  150. // only allows rows to have a memory alignement of 4.
  151. ASSERT(pixel_stride % 4 == 0);
  152. state.texture_units[0].texture_2d = texture.handle;
  153. state.Apply();
  154. glActiveTexture(GL_TEXTURE0);
  155. glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)pixel_stride);
  156. // Update existing texture
  157. // TODO: Test what happens on hardware when you change the framebuffer dimensions so that they
  158. // differ from the LCD resolution.
  159. // TODO: Applications could theoretically crash Citra here by specifying too large
  160. // framebuffer sizes. We should make sure that this cannot happen.
  161. glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, framebuffer.width, framebuffer.height,
  162. texture.gl_format, texture.gl_type, framebuffer_data);
  163. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  164. state.texture_units[0].texture_2d = 0;
  165. state.Apply();
  166. }
  167. /**
  168. * Fills active OpenGL texture with the given RGB color.
  169. * Since the color is solid, the texture can be 1x1 but will stretch across whatever it's rendered on.
  170. * This has the added benefit of being *really fast*.
  171. */
  172. void RendererOpenGL::LoadColorToActiveGLTexture(u8 color_r, u8 color_g, u8 color_b,
  173. const TextureInfo& texture) {
  174. state.texture_units[0].texture_2d = texture.handle;
  175. state.Apply();
  176. glActiveTexture(GL_TEXTURE0);
  177. u8 framebuffer_data[3] = { color_r, color_g, color_b };
  178. // Update existing texture
  179. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, framebuffer_data);
  180. }
  181. /**
  182. * Initializes the OpenGL state and creates persistent objects.
  183. */
  184. void RendererOpenGL::InitOpenGLObjects() {
  185. glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue, 0.0f);
  186. // Link shaders and get variable locations
  187. program_id = GLShader::LoadProgram(vertex_shader, fragment_shader);
  188. uniform_modelview_matrix = glGetUniformLocation(program_id, "modelview_matrix");
  189. uniform_color_texture = glGetUniformLocation(program_id, "color_texture");
  190. attrib_position = glGetAttribLocation(program_id, "vert_position");
  191. attrib_tex_coord = glGetAttribLocation(program_id, "vert_tex_coord");
  192. // Generate VBO handle for drawing
  193. glGenBuffers(1, &vertex_buffer_handle);
  194. // Generate VAO
  195. glGenVertexArrays(1, &vertex_array_handle);
  196. state.draw.vertex_array = vertex_array_handle;
  197. state.draw.vertex_buffer = vertex_buffer_handle;
  198. state.draw.uniform_buffer = 0;
  199. state.Apply();
  200. // Attach vertex data to VAO
  201. glBufferData(GL_ARRAY_BUFFER, sizeof(ScreenRectVertex) * 4, nullptr, GL_STREAM_DRAW);
  202. glVertexAttribPointer(attrib_position, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex), (GLvoid*)offsetof(ScreenRectVertex, position));
  203. glVertexAttribPointer(attrib_tex_coord, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex), (GLvoid*)offsetof(ScreenRectVertex, tex_coord));
  204. glEnableVertexAttribArray(attrib_position);
  205. glEnableVertexAttribArray(attrib_tex_coord);
  206. // Allocate textures for each screen
  207. for (auto& texture : textures) {
  208. glGenTextures(1, &texture.handle);
  209. // Allocation of storage is deferred until the first frame, when we
  210. // know the framebuffer size.
  211. state.texture_units[0].texture_2d = texture.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. }
  220. state.texture_units[0].texture_2d = 0;
  221. state.Apply();
  222. }
  223. void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
  224. const GPU::Regs::FramebufferConfig& framebuffer) {
  225. GPU::Regs::PixelFormat format = framebuffer.color_format;
  226. GLint internal_format;
  227. texture.format = format;
  228. texture.width = framebuffer.width;
  229. texture.height = framebuffer.height;
  230. switch (format) {
  231. case GPU::Regs::PixelFormat::RGBA8:
  232. internal_format = GL_RGBA;
  233. texture.gl_format = GL_RGBA;
  234. texture.gl_type = GL_UNSIGNED_INT_8_8_8_8;
  235. break;
  236. case GPU::Regs::PixelFormat::RGB8:
  237. // This pixel format uses BGR since GL_UNSIGNED_BYTE specifies byte-order, unlike every
  238. // specific OpenGL type used in this function using native-endian (that is, little-endian
  239. // mostly everywhere) for words or half-words.
  240. // TODO: check how those behave on big-endian processors.
  241. internal_format = GL_RGB;
  242. texture.gl_format = GL_BGR;
  243. texture.gl_type = GL_UNSIGNED_BYTE;
  244. break;
  245. case GPU::Regs::PixelFormat::RGB565:
  246. internal_format = GL_RGB;
  247. texture.gl_format = GL_RGB;
  248. texture.gl_type = GL_UNSIGNED_SHORT_5_6_5;
  249. break;
  250. case GPU::Regs::PixelFormat::RGB5A1:
  251. internal_format = GL_RGBA;
  252. texture.gl_format = GL_RGBA;
  253. texture.gl_type = GL_UNSIGNED_SHORT_5_5_5_1;
  254. break;
  255. case GPU::Regs::PixelFormat::RGBA4:
  256. internal_format = GL_RGBA;
  257. texture.gl_format = GL_RGBA;
  258. texture.gl_type = GL_UNSIGNED_SHORT_4_4_4_4;
  259. break;
  260. default:
  261. UNIMPLEMENTED();
  262. }
  263. state.texture_units[0].texture_2d = texture.handle;
  264. state.Apply();
  265. glActiveTexture(GL_TEXTURE0);
  266. glTexImage2D(GL_TEXTURE_2D, 0, internal_format, texture.width, texture.height, 0,
  267. texture.gl_format, texture.gl_type, nullptr);
  268. }
  269. /**
  270. * Draws a single texture to the emulator window, rotating the texture to correct for the 3DS's LCD rotation.
  271. */
  272. void RendererOpenGL::DrawSingleScreenRotated(const TextureInfo& texture, float x, float y, float w, float h) {
  273. std::array<ScreenRectVertex, 4> vertices = {{
  274. ScreenRectVertex(x, y, 1.f, 0.f),
  275. ScreenRectVertex(x+w, y, 1.f, 1.f),
  276. ScreenRectVertex(x, y+h, 0.f, 0.f),
  277. ScreenRectVertex(x+w, y+h, 0.f, 1.f),
  278. }};
  279. state.texture_units[0].texture_2d = texture.handle;
  280. state.Apply();
  281. glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices.data());
  282. glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  283. }
  284. /**
  285. * Draws the emulated screens to the emulator window.
  286. */
  287. void RendererOpenGL::DrawScreens() {
  288. auto layout = render_window->GetFramebufferLayout();
  289. glViewport(0, 0, layout.width, layout.height);
  290. glClear(GL_COLOR_BUFFER_BIT);
  291. state.draw.shader_program = program_id;
  292. state.Apply();
  293. // Set projection matrix
  294. std::array<GLfloat, 3 * 2> ortho_matrix = MakeOrthographicMatrix((float)layout.width,
  295. (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. DrawSingleScreenRotated(textures[0], (float)layout.top_screen.left, (float)layout.top_screen.top,
  301. (float)layout.top_screen.GetWidth(), (float)layout.top_screen.GetHeight());
  302. DrawSingleScreenRotated(textures[1], (float)layout.bottom_screen.left,(float)layout.bottom_screen.top,
  303. (float)layout.bottom_screen.GetWidth(), (float)layout.bottom_screen.GetHeight());
  304. m_current_frame++;
  305. }
  306. /// Updates the framerate
  307. void RendererOpenGL::UpdateFramerate() {
  308. }
  309. /**
  310. * Set the emulator window to use for renderer
  311. * @param window EmuWindow handle to emulator window to use for rendering
  312. */
  313. void RendererOpenGL::SetWindow(EmuWindow* window) {
  314. render_window = window;
  315. }
  316. static const char* GetSource(GLenum source) {
  317. #define RET(s) case GL_DEBUG_SOURCE_##s: return #s
  318. switch (source) {
  319. RET(API);
  320. RET(WINDOW_SYSTEM);
  321. RET(SHADER_COMPILER);
  322. RET(THIRD_PARTY);
  323. RET(APPLICATION);
  324. RET(OTHER);
  325. default:
  326. UNREACHABLE();
  327. }
  328. #undef RET
  329. }
  330. static const char* GetType(GLenum type) {
  331. #define RET(t) case GL_DEBUG_TYPE_##t: return #t
  332. switch (type) {
  333. RET(ERROR);
  334. RET(DEPRECATED_BEHAVIOR);
  335. RET(UNDEFINED_BEHAVIOR);
  336. RET(PORTABILITY);
  337. RET(PERFORMANCE);
  338. RET(OTHER);
  339. RET(MARKER);
  340. default:
  341. UNREACHABLE();
  342. }
  343. #undef RET
  344. }
  345. static void DebugHandler(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
  346. const GLchar* message, const void* user_param) {
  347. Log::Level level;
  348. switch (severity) {
  349. case GL_DEBUG_SEVERITY_HIGH:
  350. level = Log::Level::Error;
  351. break;
  352. case GL_DEBUG_SEVERITY_MEDIUM:
  353. level = Log::Level::Warning;
  354. break;
  355. case GL_DEBUG_SEVERITY_NOTIFICATION:
  356. case GL_DEBUG_SEVERITY_LOW:
  357. level = Log::Level::Debug;
  358. break;
  359. }
  360. LOG_GENERIC(Log::Class::Render_OpenGL, level, "%s %s %d: %s",
  361. GetSource(source), GetType(type), id, message);
  362. }
  363. /// Initialize the renderer
  364. void RendererOpenGL::Init() {
  365. render_window->MakeCurrent();
  366. // TODO: Make frontends initialize this, so they can use gladLoadGLLoader with their own loaders
  367. if (!gladLoadGL()) {
  368. LOG_CRITICAL(Render_OpenGL, "Failed to initialize GL functions! Exiting...");
  369. exit(-1);
  370. }
  371. if (GLAD_GL_KHR_debug) {
  372. glEnable(GL_DEBUG_OUTPUT);
  373. glDebugMessageCallback(DebugHandler, nullptr);
  374. }
  375. LOG_INFO(Render_OpenGL, "GL_VERSION: %s", glGetString(GL_VERSION));
  376. LOG_INFO(Render_OpenGL, "GL_VENDOR: %s", glGetString(GL_VENDOR));
  377. LOG_INFO(Render_OpenGL, "GL_RENDERER: %s", glGetString(GL_RENDERER));
  378. InitOpenGLObjects();
  379. RefreshRasterizerSetting();
  380. }
  381. /// Shutdown the renderer
  382. void RendererOpenGL::ShutDown() {
  383. }