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.

306 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-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. : owner (component)
  30. {
  31. NSOpenGLPixelFormatAttribute attribs[64] = { 0 };
  32. createAttribs (attribs, version, pixFormat, shouldUseMultisampling);
  33. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  34. static MouseForwardingNSOpenGLViewClass cls;
  35. view = [cls.createInstance() initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  36. pixelFormat: format];
  37. if ([view respondsToSelector: @selector (setWantsBestResolutionOpenGLSurface:)])
  38. [view setWantsBestResolutionOpenGLSurface: YES];
  39. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  40. [[NSNotificationCenter defaultCenter] addObserver: view
  41. selector: @selector (_surfaceNeedsUpdate:)
  42. name: NSViewGlobalFrameDidChangeNotification
  43. object: view];
  44. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  45. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  46. shareContext: (NSOpenGLContext*) contextToShare] autorelease];
  47. [view setOpenGLContext: renderContext];
  48. [format release];
  49. viewAttachment = NSViewComponent::attachViewToComponent (component, view);
  50. }
  51. ~NativeContext()
  52. {
  53. [[NSNotificationCenter defaultCenter] removeObserver: view];
  54. [renderContext clearDrawable];
  55. [renderContext setView: nil];
  56. [view setOpenGLContext: nil];
  57. [view release];
  58. }
  59. static void createAttribs (NSOpenGLPixelFormatAttribute* attribs, OpenGLVersion version,
  60. const OpenGLPixelFormat& pixFormat, bool shouldUseMultisampling)
  61. {
  62. ignoreUnused (version);
  63. int numAttribs = 0;
  64. attribs[numAttribs++] = NSOpenGLPFAOpenGLProfile;
  65. attribs[numAttribs++] = [version]
  66. {
  67. if (version == openGL3_2)
  68. return NSOpenGLProfileVersion3_2Core;
  69. if (version != defaultGLVersion)
  70. if (@available (macOS 10.10, *))
  71. return NSOpenGLProfileVersion4_1Core;
  72. return NSOpenGLProfileVersionLegacy;
  73. }();
  74. attribs[numAttribs++] = NSOpenGLPFADoubleBuffer;
  75. attribs[numAttribs++] = NSOpenGLPFAClosestPolicy;
  76. attribs[numAttribs++] = NSOpenGLPFANoRecovery;
  77. attribs[numAttribs++] = NSOpenGLPFAColorSize;
  78. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.redBits + pixFormat.greenBits + pixFormat.blueBits);
  79. attribs[numAttribs++] = NSOpenGLPFAAlphaSize;
  80. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.alphaBits;
  81. attribs[numAttribs++] = NSOpenGLPFADepthSize;
  82. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.depthBufferBits;
  83. attribs[numAttribs++] = NSOpenGLPFAStencilSize;
  84. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.stencilBufferBits;
  85. attribs[numAttribs++] = NSOpenGLPFAAccumSize;
  86. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.accumulationBufferRedBits + pixFormat.accumulationBufferGreenBits
  87. + pixFormat.accumulationBufferBlueBits + pixFormat.accumulationBufferAlphaBits);
  88. if (shouldUseMultisampling)
  89. {
  90. attribs[numAttribs++] = NSOpenGLPFAMultisample;
  91. attribs[numAttribs++] = NSOpenGLPFASampleBuffers;
  92. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) 1;
  93. attribs[numAttribs++] = NSOpenGLPFASamples;
  94. attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.multisamplingLevel;
  95. }
  96. }
  97. bool initialiseOnRenderThread (OpenGLContext&) { return true; }
  98. void shutdownOnRenderThread() { deactivateCurrentContext(); }
  99. bool createdOk() const noexcept { return getRawContext() != nullptr; }
  100. NSOpenGLContext* getRawContext() const noexcept { return renderContext; }
  101. GLuint getFrameBufferID() const noexcept { return 0; }
  102. bool makeActive() const noexcept
  103. {
  104. jassert (renderContext != nil);
  105. if ([renderContext view] != view)
  106. [renderContext setView: view];
  107. if (NSOpenGLContext* context = [view openGLContext])
  108. {
  109. [context makeCurrentContext];
  110. return true;
  111. }
  112. return false;
  113. }
  114. bool isActive() const noexcept
  115. {
  116. return [NSOpenGLContext currentContext] == renderContext;
  117. }
  118. static void deactivateCurrentContext()
  119. {
  120. [NSOpenGLContext clearCurrentContext];
  121. }
  122. struct Locker
  123. {
  124. Locker (NativeContext& nc) : cglContext ((CGLContextObj) [nc.renderContext CGLContextObj])
  125. {
  126. CGLLockContext (cglContext);
  127. }
  128. ~Locker()
  129. {
  130. CGLUnlockContext (cglContext);
  131. }
  132. private:
  133. CGLContextObj cglContext;
  134. };
  135. void swapBuffers()
  136. {
  137. auto now = Time::getMillisecondCounterHiRes();
  138. [renderContext flushBuffer];
  139. if (minSwapTimeMs > 0)
  140. {
  141. // When our window is entirely occluded by other windows, flushBuffer
  142. // fails to wait for the swap interval, so the render loop spins at full
  143. // speed, burning CPU. This hack detects when things are going too fast
  144. // and sleeps if necessary.
  145. auto swapTime = Time::getMillisecondCounterHiRes() - now;
  146. auto frameTime = (int) (now - lastSwapTime);
  147. if (swapTime < 0.5 && frameTime < minSwapTimeMs - 3)
  148. {
  149. if (underrunCounter > 3)
  150. {
  151. Thread::sleep (2 * (minSwapTimeMs - frameTime));
  152. now = Time::getMillisecondCounterHiRes();
  153. }
  154. else
  155. {
  156. ++underrunCounter;
  157. }
  158. }
  159. else
  160. {
  161. if (underrunCounter > 0)
  162. --underrunCounter;
  163. }
  164. }
  165. lastSwapTime = now;
  166. }
  167. void updateWindowPosition (Rectangle<int>)
  168. {
  169. if (auto* peer = owner.getTopLevelComponent()->getPeer())
  170. {
  171. const auto newArea = peer->getAreaCoveredBy (owner);
  172. if (convertToRectInt ([view frame]) != newArea)
  173. [view setFrame: makeNSRect (newArea)];
  174. }
  175. }
  176. bool setSwapInterval (int numFramesPerSwapIn)
  177. {
  178. numFramesPerSwap = numFramesPerSwapIn;
  179. // The macOS OpenGL programming guide says that numFramesPerSwap
  180. // can only be 0 or 1.
  181. jassert (isPositiveAndBelow (numFramesPerSwap, 2));
  182. [renderContext setValues: (const GLint*) &numFramesPerSwap
  183. forParameter: getSwapIntervalParameter()];
  184. updateMinSwapTime();
  185. return true;
  186. }
  187. int getSwapInterval() const
  188. {
  189. GLint numFrames = 0;
  190. [renderContext getValues: &numFrames
  191. forParameter: getSwapIntervalParameter()];
  192. return numFrames;
  193. }
  194. void setNominalVideoRefreshPeriodS (double periodS)
  195. {
  196. jassert (periodS > 0.0);
  197. videoRefreshPeriodS = periodS;
  198. updateMinSwapTime();
  199. }
  200. void updateMinSwapTime()
  201. {
  202. minSwapTimeMs = static_cast<int> (numFramesPerSwap * 1000 * videoRefreshPeriodS);
  203. }
  204. static NSOpenGLContextParameter getSwapIntervalParameter()
  205. {
  206. if (@available (macOS 10.12, *))
  207. return NSOpenGLContextParameterSwapInterval;
  208. return NSOpenGLCPSwapInterval;
  209. }
  210. Component& owner;
  211. NSOpenGLContext* renderContext = nil;
  212. NSOpenGLView* view = nil;
  213. ReferenceCountedObjectPtr<ReferenceCountedObject> viewAttachment;
  214. double lastSwapTime = 0;
  215. std::atomic<int> minSwapTimeMs { 0 };
  216. int underrunCounter = 0, numFramesPerSwap = 0;
  217. double videoRefreshPeriodS = 1.0 / 60.0;
  218. //==============================================================================
  219. struct MouseForwardingNSOpenGLViewClass : public ObjCClass<NSOpenGLView>
  220. {
  221. MouseForwardingNSOpenGLViewClass() : ObjCClass<NSOpenGLView> ("JUCEGLView_")
  222. {
  223. addMethod (@selector (rightMouseDown:), rightMouseDown);
  224. addMethod (@selector (rightMouseUp:), rightMouseUp);
  225. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse);
  226. addMethod (@selector (accessibilityHitTest:), accessibilityHitTest);
  227. registerClass();
  228. }
  229. private:
  230. static void rightMouseDown (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseDown: ev]; }
  231. static void rightMouseUp (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseUp: ev]; }
  232. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  233. static id accessibilityHitTest (id self, SEL, NSPoint p) { return [[(NSOpenGLView*) self superview] accessibilityHitTest: p]; }
  234. };
  235. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
  236. };
  237. //==============================================================================
  238. bool OpenGLHelpers::isContextActive()
  239. {
  240. return CGLGetCurrentContext() != CGLContextObj();
  241. }
  242. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  243. } // namespace juce