renderer_opengl.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2
  3. // Refer to the license.txt file included.
  4. #include "core/hw/gpu.h"
  5. #include "core/mem_map.h"
  6. #include "common/emu_window.h"
  7. #include "video_core/video_core.h"
  8. #include "video_core/renderer_opengl/renderer_opengl.h"
  9. #include "video_core/renderer_opengl/gl_shader_util.h"
  10. #include "video_core/renderer_opengl/gl_shaders.h"
  11. #include <algorithm>
  12. /**
  13. * Vertex structure that the drawn screen rectangles are composed of.
  14. */
  15. struct ScreenRectVertex {
  16. ScreenRectVertex(GLfloat x, GLfloat y, GLfloat u, GLfloat v) {
  17. position[0] = x;
  18. position[1] = y;
  19. tex_coord[0] = u;
  20. tex_coord[1] = v;
  21. }
  22. GLfloat position[2];
  23. GLfloat tex_coord[2];
  24. };
  25. /**
  26. * Defines a 1:1 pixel ortographic projection matrix with (0,0) on the top-left
  27. * corner and (width, height) on the lower-bottom.
  28. *
  29. * The projection part of the matrix is trivial, hence these operations are represented
  30. * by a 3x2 matrix.
  31. */
  32. static std::array<GLfloat, 3*2> MakeOrthographicMatrix(const float width, const float height) {
  33. std::array<GLfloat, 3*2> matrix;
  34. matrix[0] = 2.f / width; matrix[2] = 0.f; matrix[4] = -1.f;
  35. matrix[1] = 0.f; matrix[3] = -2.f / height; matrix[5] = 1.f;
  36. // Last matrix row is implicitly assumed to be [0, 0, 1].
  37. return matrix;
  38. }
  39. /// RendererOpenGL constructor
  40. RendererOpenGL::RendererOpenGL() {
  41. resolution_width = std::max(VideoCore::kScreenTopWidth, VideoCore::kScreenBottomWidth);
  42. resolution_height = VideoCore::kScreenTopHeight + VideoCore::kScreenBottomHeight;
  43. }
  44. /// RendererOpenGL destructor
  45. RendererOpenGL::~RendererOpenGL() {
  46. }
  47. /// Swap buffers (render frame)
  48. void RendererOpenGL::SwapBuffers() {
  49. render_window->MakeCurrent();
  50. for(int i : {0, 1}) {
  51. const auto& framebuffer = GPU::g_regs.framebuffer_config[i];
  52. if (textures[i].width != framebuffer.width || textures[i].height != framebuffer.height) {
  53. // Reallocate texture if the framebuffer size has changed.
  54. // This is expected to not happen very often and hence should not be a
  55. // performance problem.
  56. glBindTexture(GL_TEXTURE_2D, textures[i].handle);
  57. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, framebuffer.width, framebuffer.height, 0,
  58. GL_BGR, GL_UNSIGNED_BYTE, nullptr);
  59. textures[i].width = framebuffer.width;
  60. textures[i].height = framebuffer.height;
  61. }
  62. LoadFBToActiveGLTexture(GPU::g_regs.framebuffer_config[i], textures[i]);
  63. }
  64. DrawScreens();
  65. // Swap buffers
  66. render_window->PollEvents();
  67. render_window->SwapBuffers();
  68. }
  69. /**
  70. * Loads framebuffer from emulated memory into the active OpenGL texture.
  71. */
  72. void RendererOpenGL::LoadFBToActiveGLTexture(const GPU::Regs::FramebufferConfig& framebuffer,
  73. const TextureInfo& texture) {
  74. const VAddr framebuffer_vaddr = Memory::PhysicalToVirtualAddress(
  75. framebuffer.active_fb == 1 ? framebuffer.address_left2 : framebuffer.address_left1);
  76. DEBUG_LOG(GPU, "0x%08x bytes from 0x%08x(%dx%d), fmt %x",
  77. framebuffer.stride * framebuffer.height,
  78. framebuffer_vaddr, (int)framebuffer.width,
  79. (int)framebuffer.height, (int)framebuffer.format);
  80. const u8* framebuffer_data = Memory::GetPointer(framebuffer_vaddr);
  81. // TODO: Handle other pixel formats
  82. _dbg_assert_msg_(RENDER, framebuffer.color_format == GPU::Regs::PixelFormat::RGB8,
  83. "Unsupported 3DS pixel format.");
  84. size_t pixel_stride = framebuffer.stride / 3;
  85. // OpenGL only supports specifying a stride in units of pixels, not bytes, unfortunately
  86. _dbg_assert_(RENDER, pixel_stride * 3 == framebuffer.stride);
  87. // Ensure no bad interactions with GL_UNPACK_ALIGNMENT, which by default
  88. // only allows rows to have a memory alignement of 4.
  89. _dbg_assert_(RENDER, pixel_stride % 4 == 0);
  90. glBindTexture(GL_TEXTURE_2D, texture.handle);
  91. glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)pixel_stride);
  92. // Update existing texture
  93. // TODO: Test what happens on hardware when you change the framebuffer dimensions so that they
  94. // differ from the LCD resolution.
  95. // TODO: Applications could theoretically crash Citra here by specifying too large
  96. // framebuffer sizes. We should make sure that this cannot happen.
  97. glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, framebuffer.width, framebuffer.height,
  98. GL_BGR, GL_UNSIGNED_BYTE, framebuffer_data);
  99. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  100. glBindTexture(GL_TEXTURE_2D, 0);
  101. }
  102. /**
  103. * Initializes the OpenGL state and creates persistent objects.
  104. */
  105. void RendererOpenGL::InitOpenGLObjects() {
  106. glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
  107. glDisable(GL_DEPTH_TEST);
  108. // Link shaders and get variable locations
  109. program_id = ShaderUtil::LoadShaders(GLShaders::g_vertex_shader, GLShaders::g_fragment_shader);
  110. uniform_modelview_matrix = glGetUniformLocation(program_id, "modelview_matrix");
  111. uniform_color_texture = glGetUniformLocation(program_id, "color_texture");
  112. attrib_position = glGetAttribLocation(program_id, "vert_position");
  113. attrib_tex_coord = glGetAttribLocation(program_id, "vert_tex_coord");
  114. // Generate VBO handle for drawing
  115. glGenBuffers(1, &vertex_buffer_handle);
  116. // Generate VAO
  117. glGenVertexArrays(1, &vertex_array_handle);
  118. glBindVertexArray(vertex_array_handle);
  119. // Attach vertex data to VAO
  120. glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_handle);
  121. glBufferData(GL_ARRAY_BUFFER, sizeof(ScreenRectVertex) * 4, nullptr, GL_STREAM_DRAW);
  122. glVertexAttribPointer(attrib_position, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex), (GLvoid*)offsetof(ScreenRectVertex, position));
  123. glVertexAttribPointer(attrib_tex_coord, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex), (GLvoid*)offsetof(ScreenRectVertex, tex_coord));
  124. glEnableVertexAttribArray(attrib_position);
  125. glEnableVertexAttribArray(attrib_tex_coord);
  126. // Allocate textures for each screen
  127. for (auto& texture : textures) {
  128. glGenTextures(1, &texture.handle);
  129. // Allocation of storage is deferred until the first frame, when we
  130. // know the framebuffer size.
  131. glBindTexture(GL_TEXTURE_2D, texture.handle);
  132. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
  133. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  134. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  135. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  136. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  137. }
  138. glBindTexture(GL_TEXTURE_2D, 0);
  139. }
  140. /**
  141. * Draws a single texture to the emulator window, rotating the texture to correct for the 3DS's LCD rotation.
  142. */
  143. void RendererOpenGL::DrawSingleScreenRotated(const TextureInfo& texture, float x, float y, float w, float h) {
  144. std::array<ScreenRectVertex, 4> vertices = {
  145. ScreenRectVertex(x, y, 1.f, 0.f),
  146. ScreenRectVertex(x+w, y, 1.f, 1.f),
  147. ScreenRectVertex(x, y+h, 0.f, 0.f),
  148. ScreenRectVertex(x+w, y+h, 0.f, 1.f),
  149. };
  150. glBindTexture(GL_TEXTURE_2D, texture.handle);
  151. glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_handle);
  152. glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices.data());
  153. glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  154. }
  155. /**
  156. * Draws the emulated screens to the emulator window.
  157. */
  158. void RendererOpenGL::DrawScreens() {
  159. auto viewport_extent = GetViewportExtent();
  160. glViewport(viewport_extent.left, viewport_extent.top, viewport_extent.GetWidth(), viewport_extent.GetHeight()); // TODO: Or bottom?
  161. glClear(GL_COLOR_BUFFER_BIT);
  162. glUseProgram(program_id);
  163. // Set projection matrix
  164. std::array<GLfloat, 3*2> ortho_matrix = MakeOrthographicMatrix((float)resolution_width, (float)resolution_height);
  165. glUniformMatrix3x2fv(uniform_modelview_matrix, 1, GL_FALSE, ortho_matrix.data());
  166. // Bind texture in Texture Unit 0
  167. glActiveTexture(GL_TEXTURE0);
  168. glUniform1i(uniform_color_texture, 0);
  169. const float max_width = std::max((float)VideoCore::kScreenTopWidth, (float)VideoCore::kScreenBottomWidth);
  170. const float top_x = 0.5f * (max_width - VideoCore::kScreenTopWidth);
  171. const float bottom_x = 0.5f * (max_width - VideoCore::kScreenBottomWidth);
  172. DrawSingleScreenRotated(textures[0], top_x, 0,
  173. (float)VideoCore::kScreenTopWidth, (float)VideoCore::kScreenTopHeight);
  174. DrawSingleScreenRotated(textures[1], bottom_x, (float)VideoCore::kScreenTopHeight,
  175. (float)VideoCore::kScreenBottomWidth, (float)VideoCore::kScreenBottomHeight);
  176. m_current_frame++;
  177. }
  178. /// Updates the framerate
  179. void RendererOpenGL::UpdateFramerate() {
  180. }
  181. /**
  182. * Set the emulator window to use for renderer
  183. * @param window EmuWindow handle to emulator window to use for rendering
  184. */
  185. void RendererOpenGL::SetWindow(EmuWindow* window) {
  186. render_window = window;
  187. }
  188. MathUtil::Rectangle<unsigned> RendererOpenGL::GetViewportExtent() {
  189. unsigned framebuffer_width;
  190. unsigned framebuffer_height;
  191. std::tie(framebuffer_width, framebuffer_height) = render_window->GetFramebufferSize();
  192. float window_aspect_ratio = static_cast<float>(framebuffer_height) / framebuffer_width;
  193. float emulation_aspect_ratio = static_cast<float>(resolution_height) / resolution_width;
  194. MathUtil::Rectangle<unsigned> viewport_extent;
  195. if (window_aspect_ratio > emulation_aspect_ratio) {
  196. // Window is narrower than the emulation content => apply borders to the top and bottom
  197. unsigned viewport_height = emulation_aspect_ratio * framebuffer_width;
  198. viewport_extent.left = 0;
  199. viewport_extent.top = (framebuffer_height - viewport_height) / 2;
  200. viewport_extent.right = viewport_extent.left + framebuffer_width;
  201. viewport_extent.bottom = viewport_extent.top + viewport_height;
  202. } else {
  203. // Otherwise, apply borders to the left and right sides of the window.
  204. unsigned viewport_width = framebuffer_height / emulation_aspect_ratio;
  205. viewport_extent.left = (framebuffer_width - viewport_width) / 2;
  206. viewport_extent.top = 0;
  207. viewport_extent.right = viewport_extent.left + viewport_width;
  208. viewport_extent.bottom = viewport_extent.top + framebuffer_height;
  209. }
  210. return viewport_extent;
  211. }
  212. /// Initialize the renderer
  213. void RendererOpenGL::Init() {
  214. render_window->MakeCurrent();
  215. int err = ogl_LoadFunctions();
  216. if (ogl_LOAD_SUCCEEDED != err) {
  217. ERROR_LOG(RENDER, "Failed to initialize GL functions! Exiting...");
  218. exit(-1);
  219. }
  220. NOTICE_LOG(RENDER, "GL_VERSION: %s\n", glGetString(GL_VERSION));
  221. InitOpenGLObjects();
  222. }
  223. /// Shutdown the renderer
  224. void RendererOpenGL::ShutDown() {
  225. }