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.

287 lines
10KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  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 ([view respondsToSelector: @selector (setWantsBestResolutionOpenGLSurface:)])
  37. [view setWantsBestResolutionOpenGLSurface: YES];
  38. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  39. [[NSNotificationCenter defaultCenter] addObserver: view
  40. selector: @selector (_surfaceNeedsUpdate:)
  41. name: NSViewGlobalFrameDidChangeNotification
  42. object: view];
  43. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  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. attribs[numAttribs++] = NSOpenGLPFAOpenGLProfile;
  64. attribs[numAttribs++] = version >= openGL3_2 ? NSOpenGLProfileVersion3_2Core
  65. : NSOpenGLProfileVersionLegacy;
  66. attribs[numAttribs++] = NSOpenGLPFADoubleBuffer;
  67. attribs[numAttribs++] = NSOpenGLPFAClosestPolicy;
  68. attribs[numAttribs++] = NSOpenGLPFANoRecovery;
  69. attribs[numAttribs++] = NSOpenGLPFAColorSize;
  70. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.redBits + pixFormat.greenBits + pixFormat.blueBits);
  71. attribs[numAttribs++] = NSOpenGLPFAAlphaSize;
  72. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.alphaBits;
  73. attribs[numAttribs++] = NSOpenGLPFADepthSize;
  74. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.depthBufferBits;
  75. attribs[numAttribs++] = NSOpenGLPFAStencilSize;
  76. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.stencilBufferBits;
  77. attribs[numAttribs++] = NSOpenGLPFAAccumSize;
  78. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.accumulationBufferRedBits + pixFormat.accumulationBufferGreenBits
  79. + pixFormat.accumulationBufferBlueBits + pixFormat.accumulationBufferAlphaBits);
  80. if (shouldUseMultisampling)
  81. {
  82. attribs[numAttribs++] = NSOpenGLPFAMultisample;
  83. attribs[numAttribs++] = NSOpenGLPFASampleBuffers;
  84. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) 1;
  85. attribs[numAttribs++] = NSOpenGLPFASamples;
  86. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.multisamplingLevel;
  87. }
  88. }
  89. bool initialiseOnRenderThread (OpenGLContext&) { return true; }
  90. void shutdownOnRenderThread() { deactivateCurrentContext(); }
  91. bool createdOk() const noexcept { return getRawContext() != nullptr; }
  92. void* getRawContext() const noexcept { return static_cast<void*> (renderContext); }
  93. GLuint getFrameBufferID() const noexcept { return 0; }
  94. bool makeActive() const noexcept
  95. {
  96. jassert (renderContext != nil);
  97. if ([renderContext view] != view)
  98. [renderContext setView: view];
  99. if (NSOpenGLContext* context = [view openGLContext])
  100. {
  101. [context makeCurrentContext];
  102. return true;
  103. }
  104. return false;
  105. }
  106. bool isActive() const noexcept
  107. {
  108. return [NSOpenGLContext currentContext] == renderContext;
  109. }
  110. static void deactivateCurrentContext()
  111. {
  112. [NSOpenGLContext clearCurrentContext];
  113. }
  114. struct Locker
  115. {
  116. Locker (NativeContext& nc) : cglContext ((CGLContextObj) [nc.renderContext CGLContextObj])
  117. {
  118. CGLLockContext (cglContext);
  119. }
  120. ~Locker()
  121. {
  122. CGLUnlockContext (cglContext);
  123. }
  124. private:
  125. CGLContextObj cglContext;
  126. };
  127. void swapBuffers()
  128. {
  129. auto now = Time::getMillisecondCounterHiRes();
  130. [renderContext flushBuffer];
  131. if (minSwapTimeMs > 0)
  132. {
  133. // When our window is entirely occluded by other windows, flushBuffer
  134. // fails to wait for the swap interval, so the render loop spins at full
  135. // speed, burning CPU. This hack detects when things are going too fast
  136. // and sleeps if necessary.
  137. auto swapTime = Time::getMillisecondCounterHiRes() - now;
  138. auto frameTime = (int) (now - lastSwapTime);
  139. if (swapTime < 0.5 && frameTime < minSwapTimeMs - 3)
  140. {
  141. if (underrunCounter > 3)
  142. {
  143. Thread::sleep (2 * (minSwapTimeMs - frameTime));
  144. now = Time::getMillisecondCounterHiRes();
  145. }
  146. else
  147. {
  148. ++underrunCounter;
  149. }
  150. }
  151. else
  152. {
  153. if (underrunCounter > 0)
  154. --underrunCounter;
  155. }
  156. }
  157. lastSwapTime = now;
  158. }
  159. void updateWindowPosition (Rectangle<int>) {}
  160. bool setSwapInterval (int numFramesPerSwapIn)
  161. {
  162. numFramesPerSwap = numFramesPerSwapIn;
  163. // The macOS OpenGL programming guide says that numFramesPerSwap
  164. // can only be 0 or 1.
  165. jassert (isPositiveAndBelow (numFramesPerSwap, 2));
  166. [renderContext setValues: (const GLint*) &numFramesPerSwap
  167. forParameter: getSwapIntervalParameter()];
  168. updateMinSwapTime();
  169. return true;
  170. }
  171. int getSwapInterval() const
  172. {
  173. GLint numFrames = 0;
  174. [renderContext getValues: &numFrames
  175. forParameter: getSwapIntervalParameter()];
  176. return numFrames;
  177. }
  178. void setNominalVideoRefreshPeriodS (double periodS)
  179. {
  180. jassert (periodS > 0.0);
  181. videoRefreshPeriodS = periodS;
  182. updateMinSwapTime();
  183. }
  184. void updateMinSwapTime()
  185. {
  186. minSwapTimeMs = static_cast<int> (numFramesPerSwap * 1000 * videoRefreshPeriodS);
  187. }
  188. static NSOpenGLContextParameter getSwapIntervalParameter()
  189. {
  190. #if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12
  191. if (@available (macOS 10.12, *))
  192. return NSOpenGLContextParameterSwapInterval;
  193. #endif
  194. return NSOpenGLCPSwapInterval;
  195. }
  196. NSOpenGLContext* renderContext = nil;
  197. NSOpenGLView* view = nil;
  198. ReferenceCountedObjectPtr<ReferenceCountedObject> viewAttachment;
  199. double lastSwapTime = 0;
  200. int minSwapTimeMs = 0, underrunCounter = 0, numFramesPerSwap = 0;
  201. double videoRefreshPeriodS = 1.0 / 60.0;
  202. //==============================================================================
  203. struct MouseForwardingNSOpenGLViewClass : public ObjCClass<NSOpenGLView>
  204. {
  205. MouseForwardingNSOpenGLViewClass() : ObjCClass<NSOpenGLView> ("JUCEGLView_")
  206. {
  207. addMethod (@selector (rightMouseDown:), rightMouseDown);
  208. addMethod (@selector (rightMouseUp:), rightMouseUp);
  209. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse);
  210. addMethod (@selector (accessibilityHitTest:), accessibilityHitTest);
  211. registerClass();
  212. }
  213. private:
  214. static void rightMouseDown (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseDown: ev]; }
  215. static void rightMouseUp (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseUp: ev]; }
  216. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  217. static id accessibilityHitTest (id self, SEL, NSPoint p) { return [[(NSOpenGLView*) self superview] accessibilityHitTest: p]; }
  218. };
  219. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
  220. };
  221. //==============================================================================
  222. bool OpenGLHelpers::isContextActive()
  223. {
  224. return CGLGetCurrentContext() != CGLContextObj();
  225. }
  226. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  227. } // namespace juce