embedded_gl_manager.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /**************************************************************************/
  2. /* embedded_gl_manager.mm */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #import "embedded_gl_manager.h"
  31. #import "drivers/gles3/storage/texture_storage.h"
  32. #import "platform_gl.h"
  33. #if defined(MACOS_ENABLED) && defined(GLES3_ENABLED)
  34. #import <QuartzCore/QuartzCore.h>
  35. #include <dlfcn.h>
  36. GODOT_CLANG_WARNING_PUSH_AND_IGNORE("-Wdeprecated-declarations") // OpenGL is deprecated in macOS 10.14.
  37. Error GLManagerEmbedded::create_context(GLWindow &p_win) {
  38. NSOpenGLPixelFormatAttribute attributes[] = {
  39. NSOpenGLPFADoubleBuffer,
  40. NSOpenGLPFAClosestPolicy,
  41. NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core,
  42. NSOpenGLPFAColorSize, 32,
  43. NSOpenGLPFADepthSize, 24,
  44. NSOpenGLPFAStencilSize, 8,
  45. 0
  46. };
  47. NSOpenGLPixelFormat *pixel_format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes];
  48. ERR_FAIL_NULL_V(pixel_format, ERR_CANT_CREATE);
  49. p_win.context = [[NSOpenGLContext alloc] initWithFormat:pixel_format shareContext:shared_context];
  50. ERR_FAIL_NULL_V(p_win.context, ERR_CANT_CREATE);
  51. if (shared_context == nullptr) {
  52. shared_context = p_win.context;
  53. }
  54. [p_win.context makeCurrentContext];
  55. return OK;
  56. }
  57. Error GLManagerEmbedded::window_create(DisplayServer::WindowID p_window_id, CALayer *p_layer, int p_width, int p_height) {
  58. GLWindow win;
  59. win.layer = p_layer;
  60. win.width = 0;
  61. win.height = 0;
  62. if (create_context(win) != OK) {
  63. return FAILED;
  64. }
  65. windows[p_window_id] = win;
  66. window_make_current(p_window_id);
  67. return OK;
  68. }
  69. void GLManagerEmbedded::window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height) {
  70. GLWindowElement *el = windows.find(p_window_id);
  71. ERR_FAIL_NULL_MSG(el, "Window resize failed: window does not exist.");
  72. GLWindow &win = el->get();
  73. if (win.width == (uint32_t)p_width && win.height == (uint32_t)p_height) {
  74. return;
  75. }
  76. win.width = (uint32_t)p_width;
  77. win.height = (uint32_t)p_height;
  78. win.destroy_framebuffers();
  79. for (FrameBuffer &fb : win.framebuffers) {
  80. NSDictionary *surfaceProps = @{
  81. (NSString *)kIOSurfaceWidth : @(p_width),
  82. (NSString *)kIOSurfaceHeight : @(p_height),
  83. (NSString *)kIOSurfaceBytesPerElement : @(4),
  84. (NSString *)kIOSurfacePixelFormat : @(kCVPixelFormatType_32BGRA),
  85. };
  86. fb.surface = IOSurfaceCreate((__bridge CFDictionaryRef)surfaceProps);
  87. if (fb.surface == nullptr) {
  88. ERR_PRINT(vformat("Failed to create IOSurface: width=%d, height=%d", p_width, p_height));
  89. win.destroy_framebuffers();
  90. return;
  91. }
  92. glGenTextures(1, &fb.tex);
  93. glBindTexture(GL_TEXTURE_RECTANGLE, fb.tex);
  94. glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  95. glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  96. glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  97. glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  98. CGLError err = CGLTexImageIOSurface2D(CGLGetCurrentContext(),
  99. GL_TEXTURE_RECTANGLE,
  100. GL_RGBA,
  101. p_width,
  102. p_height,
  103. GL_BGRA,
  104. GL_UNSIGNED_INT_8_8_8_8_REV,
  105. fb.surface,
  106. 0);
  107. if (err != kCGLNoError) {
  108. String err_string = String(CGLErrorString(err));
  109. ERR_PRINT(vformat("CGLTexImageIOSurface2D failed (%d): %s", err, err_string));
  110. win.destroy_framebuffers();
  111. return;
  112. }
  113. glGenFramebuffers(1, &fb.fbo);
  114. glBindFramebuffer(GL_FRAMEBUFFER, fb.fbo);
  115. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE, fb.tex, 0);
  116. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
  117. ERR_PRINT("Unable to create framebuffer from IOSurface texture.");
  118. win.destroy_framebuffers();
  119. return;
  120. }
  121. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  122. glBindTexture(GL_TEXTURE_RECTANGLE, 0);
  123. }
  124. win.current_fb = 0;
  125. GLES3::TextureStorage::system_fbo = win.framebuffers[win.current_fb].fbo;
  126. win.is_valid = true;
  127. }
  128. void GLManagerEmbedded::GLWindow::destroy_framebuffers() {
  129. is_valid = false;
  130. GLES3::TextureStorage::system_fbo = 0;
  131. for (FrameBuffer &fb : framebuffers) {
  132. if (fb.fbo) {
  133. glDeleteFramebuffers(1, &fb.fbo);
  134. fb.fbo = 0;
  135. }
  136. if (fb.tex) {
  137. glDeleteTextures(1, &fb.tex);
  138. fb.tex = 0;
  139. }
  140. if (fb.surface) {
  141. IOSurfaceRef old_surface = fb.surface;
  142. fb.surface = nullptr;
  143. CFRelease(old_surface);
  144. }
  145. }
  146. }
  147. Size2i GLManagerEmbedded::window_get_size(DisplayServer::WindowID p_window_id) const {
  148. const GLWindowElement *el = windows.find(p_window_id);
  149. if (el == nullptr) {
  150. return Size2i();
  151. }
  152. const GLWindow &win = el->value();
  153. return Size2i(win.width, win.height);
  154. }
  155. void GLManagerEmbedded::window_destroy(DisplayServer::WindowID p_window_id) {
  156. GLWindowElement *el = windows.find(p_window_id);
  157. if (el == nullptr) {
  158. return;
  159. }
  160. if (current_window == p_window_id) {
  161. current_window = DisplayServer::INVALID_WINDOW_ID;
  162. }
  163. windows.erase(el);
  164. }
  165. void GLManagerEmbedded::release_current() {
  166. if (current_window == DisplayServer::INVALID_WINDOW_ID) {
  167. return;
  168. }
  169. [NSOpenGLContext clearCurrentContext];
  170. current_window = DisplayServer::INVALID_WINDOW_ID;
  171. }
  172. void GLManagerEmbedded::window_make_current(DisplayServer::WindowID p_window_id) {
  173. if (current_window == p_window_id) {
  174. return;
  175. }
  176. const GLWindowElement *el = windows.find(p_window_id);
  177. if (el == nullptr) {
  178. return;
  179. }
  180. const GLWindow &win = el->value();
  181. [win.context makeCurrentContext];
  182. current_window = p_window_id;
  183. }
  184. void GLManagerEmbedded::swap_buffers() {
  185. GLWindow &win = windows[current_window];
  186. [win.context flushBuffer];
  187. static bool last_valid = false;
  188. if (!win.is_valid) {
  189. if (last_valid) {
  190. ERR_PRINT("GLWindow framebuffers are invalid.");
  191. last_valid = false;
  192. }
  193. return;
  194. }
  195. last_valid = true;
  196. if (display_link_running) {
  197. dispatch_semaphore_wait(display_semaphore, DISPATCH_TIME_FOREVER);
  198. }
  199. [CATransaction begin];
  200. [CATransaction setDisableActions:YES];
  201. win.layer.contents = (__bridge id)win.framebuffers[win.current_fb].surface;
  202. [CATransaction commit];
  203. win.current_fb = (win.current_fb + 1) % BUFFER_COUNT;
  204. GLES3::TextureStorage::system_fbo = win.framebuffers[win.current_fb].fbo;
  205. }
  206. Error GLManagerEmbedded::initialize() {
  207. return framework_loaded ? OK : ERR_CANT_CREATE;
  208. }
  209. void GLManagerEmbedded::create_display_link() {
  210. DEV_ASSERT(display_link == nullptr);
  211. CVReturn err = CVDisplayLinkCreateWithCGDisplay(CGMainDisplayID(), &display_link);
  212. ERR_FAIL_COND_MSG(err != kCVReturnSuccess, "Failed to create display link.");
  213. __block dispatch_semaphore_t local_semaphore = display_semaphore;
  214. CVDisplayLinkSetOutputHandler(display_link, ^CVReturn(CVDisplayLinkRef p_display_link, const CVTimeStamp *p_now, const CVTimeStamp *p_output_time, CVOptionFlags p_flags, CVOptionFlags *p_flags_out) {
  215. dispatch_semaphore_signal(local_semaphore);
  216. return kCVReturnSuccess;
  217. });
  218. }
  219. void GLManagerEmbedded::release_display_link() {
  220. DEV_ASSERT(display_link != nullptr);
  221. if (CVDisplayLinkIsRunning(display_link)) {
  222. CVDisplayLinkStop(display_link);
  223. }
  224. CVDisplayLinkRelease(display_link);
  225. display_link = nullptr;
  226. }
  227. void GLManagerEmbedded::set_display_id(uint32_t p_display_id) {
  228. if (display_id == p_display_id) {
  229. return;
  230. }
  231. CVReturn err = CVDisplayLinkSetCurrentCGDisplay(display_link, static_cast<CGDirectDisplayID>(p_display_id));
  232. ERR_FAIL_COND_MSG(err != kCVReturnSuccess, "Failed to set display ID for display link.");
  233. }
  234. void GLManagerEmbedded::set_vsync_enabled(bool p_enabled) {
  235. if (p_enabled == vsync_enabled) {
  236. return;
  237. }
  238. vsync_enabled = p_enabled;
  239. if (vsync_enabled) {
  240. if (!CVDisplayLinkIsRunning(display_link)) {
  241. CVReturn err = CVDisplayLinkStart(display_link);
  242. ERR_FAIL_COND_MSG(err != kCVReturnSuccess, "Failed to start display link.");
  243. display_link_running = true;
  244. }
  245. } else {
  246. if (CVDisplayLinkIsRunning(display_link)) {
  247. CVReturn err = CVDisplayLinkStop(display_link);
  248. ERR_FAIL_COND_MSG(err != kCVReturnSuccess, "Failed to stop display link.");
  249. display_link_running = false;
  250. }
  251. }
  252. }
  253. GLManagerEmbedded::GLManagerEmbedded() {
  254. display_semaphore = dispatch_semaphore_create(BUFFER_COUNT);
  255. create_display_link();
  256. NSBundle *framework = [NSBundle bundleWithIdentifier:@"com.apple.opengl"];
  257. if ([framework load]) {
  258. void *library_handle = dlopen([framework.executablePath UTF8String], RTLD_NOW);
  259. if (library_handle) {
  260. CGLGetCurrentContext = (CGLGetCurrentContextPtr)dlsym(library_handle, "CGLGetCurrentContext");
  261. CGLTexImageIOSurface2D = (CGLTexImageIOSurface2DPtr)dlsym(library_handle, "CGLTexImageIOSurface2D");
  262. CGLErrorString = (CGLErrorStringPtr)dlsym(library_handle, "CGLErrorString");
  263. framework_loaded = CGLGetCurrentContext && CGLTexImageIOSurface2D && CGLErrorString;
  264. }
  265. }
  266. }
  267. GLManagerEmbedded::~GLManagerEmbedded() {
  268. release_display_link();
  269. release_current();
  270. }
  271. GODOT_CLANG_WARNING_POP
  272. #endif // MACOS_ENABLED && GLES3_ENABLED