The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

258 lines
9.4KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. class OpenGLContext::NativeContext
  22. {
  23. public:
  24. NativeContext (Component& component,
  25. const OpenGLPixelFormat& pixFormat,
  26. void* contextToShare,
  27. bool shouldUseMultisampling,
  28. OpenGLVersion version)
  29. {
  30. NSOpenGLPixelFormatAttribute attribs[64] = { 0 };
  31. createAttribs (attribs, version, pixFormat, shouldUseMultisampling);
  32. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  33. static MouseForwardingNSOpenGLViewClass cls;
  34. view = [cls.createInstance() initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  35. pixelFormat: format];
  36. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
  37. if ([view respondsToSelector: @selector (setWantsBestResolutionOpenGLSurface:)])
  38. [view setWantsBestResolutionOpenGLSurface: YES];
  39. #endif
  40. [[NSNotificationCenter defaultCenter] addObserver: view
  41. selector: @selector (_surfaceNeedsUpdate:)
  42. name: NSViewGlobalFrameDidChangeNotification
  43. object: view];
  44. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  45. shareContext: (NSOpenGLContext*) contextToShare] autorelease];
  46. [view setOpenGLContext: renderContext];
  47. [format release];
  48. viewAttachment = NSViewComponent::attachViewToComponent (component, view);
  49. }
  50. ~NativeContext()
  51. {
  52. [[NSNotificationCenter defaultCenter] removeObserver: view];
  53. [renderContext clearDrawable];
  54. [renderContext setView: nil];
  55. [view setOpenGLContext: nil];
  56. [view release];
  57. }
  58. static void createAttribs (NSOpenGLPixelFormatAttribute* attribs, OpenGLVersion version,
  59. const OpenGLPixelFormat& pixFormat, bool shouldUseMultisampling)
  60. {
  61. ignoreUnused (version);
  62. int numAttribs = 0;
  63. #if JUCE_OPENGL3
  64. attribs[numAttribs++] = NSOpenGLPFAOpenGLProfile;
  65. attribs[numAttribs++] = version >= openGL3_2 ? NSOpenGLProfileVersion3_2Core
  66. : NSOpenGLProfileVersionLegacy;
  67. #endif
  68. attribs[numAttribs++] = NSOpenGLPFADoubleBuffer;
  69. attribs[numAttribs++] = NSOpenGLPFAClosestPolicy;
  70. attribs[numAttribs++] = NSOpenGLPFANoRecovery;
  71. attribs[numAttribs++] = NSOpenGLPFAColorSize;
  72. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.redBits + pixFormat.greenBits + pixFormat.blueBits);
  73. attribs[numAttribs++] = NSOpenGLPFAAlphaSize;
  74. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.alphaBits;
  75. attribs[numAttribs++] = NSOpenGLPFADepthSize;
  76. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.depthBufferBits;
  77. attribs[numAttribs++] = NSOpenGLPFAStencilSize;
  78. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.stencilBufferBits;
  79. attribs[numAttribs++] = NSOpenGLPFAAccumSize;
  80. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.accumulationBufferRedBits + pixFormat.accumulationBufferGreenBits
  81. + pixFormat.accumulationBufferBlueBits + pixFormat.accumulationBufferAlphaBits);
  82. if (shouldUseMultisampling)
  83. {
  84. attribs[numAttribs++] = NSOpenGLPFAMultisample;
  85. attribs[numAttribs++] = NSOpenGLPFASampleBuffers;
  86. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) 1;
  87. attribs[numAttribs++] = NSOpenGLPFASamples;
  88. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.multisamplingLevel;
  89. }
  90. }
  91. bool initialiseOnRenderThread (OpenGLContext&) { return true; }
  92. void shutdownOnRenderThread() { deactivateCurrentContext(); }
  93. bool createdOk() const noexcept { return getRawContext() != nullptr; }
  94. void* getRawContext() const noexcept { return static_cast<void*> (renderContext); }
  95. GLuint getFrameBufferID() const noexcept { return 0; }
  96. bool makeActive() const noexcept
  97. {
  98. jassert (renderContext != nil);
  99. if ([renderContext view] != view)
  100. [renderContext setView: view];
  101. if (NSOpenGLContext* context = [view openGLContext])
  102. {
  103. [context makeCurrentContext];
  104. return true;
  105. }
  106. return false;
  107. }
  108. bool isActive() const noexcept
  109. {
  110. return [NSOpenGLContext currentContext] == renderContext;
  111. }
  112. static void deactivateCurrentContext()
  113. {
  114. [NSOpenGLContext clearCurrentContext];
  115. }
  116. struct Locker
  117. {
  118. Locker (NativeContext& nc) : cglContext ((CGLContextObj) [nc.renderContext CGLContextObj])
  119. {
  120. CGLLockContext (cglContext);
  121. }
  122. ~Locker()
  123. {
  124. CGLUnlockContext (cglContext);
  125. }
  126. private:
  127. CGLContextObj cglContext;
  128. };
  129. void swapBuffers()
  130. {
  131. auto now = Time::getMillisecondCounterHiRes();
  132. [renderContext flushBuffer];
  133. if (minSwapTimeMs > 0)
  134. {
  135. // When our window is entirely occluded by other windows, flushBuffer
  136. // fails to wait for the swap interval, so the render loop spins at full
  137. // speed, burning CPU. This hack detects when things are going too fast
  138. // and sleeps if necessary.
  139. auto swapTime = Time::getMillisecondCounterHiRes() - now;
  140. auto frameTime = (int) (now - lastSwapTime);
  141. if (swapTime < 0.5 && frameTime < minSwapTimeMs - 3)
  142. {
  143. if (underrunCounter > 3)
  144. {
  145. Thread::sleep (2 * (minSwapTimeMs - frameTime));
  146. now = Time::getMillisecondCounterHiRes();
  147. }
  148. else
  149. {
  150. ++underrunCounter;
  151. }
  152. }
  153. else
  154. {
  155. if (underrunCounter > 0)
  156. --underrunCounter;
  157. }
  158. }
  159. lastSwapTime = now;
  160. }
  161. void updateWindowPosition (Rectangle<int>) {}
  162. bool setSwapInterval (int numFramesPerSwap)
  163. {
  164. // The macOS OpenGL programming guide says that numFramesPerSwap
  165. // can only be 0 or 1.
  166. jassert (isPositiveAndBelow (numFramesPerSwap, 2));
  167. minSwapTimeMs = (numFramesPerSwap * 1000) / 60;
  168. [renderContext setValues: (const GLint*) &numFramesPerSwap
  169. forParameter: NSOpenGLCPSwapInterval];
  170. return true;
  171. }
  172. int getSwapInterval() const
  173. {
  174. GLint numFrames = 0;
  175. [renderContext getValues: &numFrames
  176. forParameter: NSOpenGLCPSwapInterval];
  177. return numFrames;
  178. }
  179. NSOpenGLContext* renderContext = nil;
  180. NSOpenGLView* view = nil;
  181. ReferenceCountedObjectPtr<ReferenceCountedObject> viewAttachment;
  182. double lastSwapTime = 0;
  183. int minSwapTimeMs = 0, underrunCounter = 0;
  184. //==============================================================================
  185. struct MouseForwardingNSOpenGLViewClass : public ObjCClass<NSOpenGLView>
  186. {
  187. MouseForwardingNSOpenGLViewClass() : ObjCClass<NSOpenGLView> ("JUCEGLView_")
  188. {
  189. addMethod (@selector (rightMouseDown:), rightMouseDown, "v@:@");
  190. addMethod (@selector (rightMouseUp:), rightMouseUp, "v@:@");
  191. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse, "v@:@");
  192. registerClass();
  193. }
  194. private:
  195. static void rightMouseDown (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseDown: ev]; }
  196. static void rightMouseUp (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseUp: ev]; }
  197. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  198. };
  199. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
  200. };
  201. //==============================================================================
  202. bool OpenGLHelpers::isContextActive()
  203. {
  204. return CGLGetCurrentContext() != CGLContextObj();
  205. }
  206. } // namespace juce