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.

398 lines
15KB

  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. extern ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component&, void* parent);
  21. //==============================================================================
  22. class OpenGLContext::NativeContext : private ComponentPeer::ScaleFactorListener
  23. {
  24. public:
  25. NativeContext (Component& component,
  26. const OpenGLPixelFormat& pixelFormat,
  27. void* contextToShareWithIn,
  28. bool /*useMultisampling*/,
  29. OpenGLVersion version)
  30. {
  31. dummyComponent.reset (new DummyComponent (*this));
  32. createNativeWindow (component);
  33. PIXELFORMATDESCRIPTOR pfd;
  34. initialisePixelFormatDescriptor (pfd, pixelFormat);
  35. auto pixFormat = ChoosePixelFormat (dc.get(), &pfd);
  36. if (pixFormat != 0)
  37. SetPixelFormat (dc.get(), pixFormat, &pfd);
  38. initialiseWGLExtensions (dc.get());
  39. renderContext.reset (createRenderContext (version, dc.get()));
  40. if (renderContext != nullptr)
  41. {
  42. makeActive();
  43. auto wglFormat = wglChoosePixelFormatExtension (pixelFormat);
  44. deactivateCurrentContext();
  45. if (wglFormat != pixFormat && wglFormat != 0)
  46. {
  47. // can't change the pixel format of a window, so need to delete the
  48. // old one and create a new one.
  49. dc.reset();
  50. nativeWindow = nullptr;
  51. createNativeWindow (component);
  52. if (SetPixelFormat (dc.get(), wglFormat, &pfd))
  53. {
  54. renderContext.reset();
  55. renderContext.reset (createRenderContext (version, dc.get()));
  56. }
  57. }
  58. if (contextToShareWithIn != nullptr)
  59. wglShareLists ((HGLRC) contextToShareWithIn, renderContext.get());
  60. component.getTopLevelComponent()->repaint();
  61. component.repaint();
  62. }
  63. }
  64. ~NativeContext() override
  65. {
  66. renderContext.reset();
  67. dc.reset();
  68. if (safeComponent != nullptr)
  69. if (auto* peer = safeComponent->getTopLevelComponent()->getPeer())
  70. peer->removeScaleFactorListener (this);
  71. }
  72. InitResult initialiseOnRenderThread (OpenGLContext& c)
  73. {
  74. threadAwarenessSetter = std::make_unique<ScopedThreadDPIAwarenessSetter> (nativeWindow->getNativeHandle());
  75. context = &c;
  76. return InitResult::success;
  77. }
  78. void shutdownOnRenderThread()
  79. {
  80. deactivateCurrentContext();
  81. context = nullptr;
  82. threadAwarenessSetter = nullptr;
  83. }
  84. static void deactivateCurrentContext() { wglMakeCurrent (nullptr, nullptr); }
  85. bool makeActive() const noexcept { return isActive() || wglMakeCurrent (dc.get(), renderContext.get()) != FALSE; }
  86. bool isActive() const noexcept { return wglGetCurrentContext() == renderContext.get(); }
  87. void swapBuffers() const noexcept { SwapBuffers (dc.get()); }
  88. bool setSwapInterval (int numFramesPerSwap)
  89. {
  90. jassert (isActive()); // this can only be called when the context is active..
  91. return wglSwapIntervalEXT != nullptr && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  92. }
  93. int getSwapInterval() const
  94. {
  95. jassert (isActive()); // this can only be called when the context is active..
  96. return wglGetSwapIntervalEXT != nullptr ? wglGetSwapIntervalEXT() : 0;
  97. }
  98. void updateWindowPosition (Rectangle<int> bounds)
  99. {
  100. if (nativeWindow != nullptr)
  101. {
  102. if (! approximatelyEqual (nativeScaleFactor, 1.0))
  103. bounds = (bounds.toDouble() * nativeScaleFactor).toNearestInt();
  104. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), nullptr,
  105. bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  106. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  107. }
  108. }
  109. bool createdOk() const noexcept { return getRawContext() != nullptr; }
  110. void* getRawContext() const noexcept { return renderContext.get(); }
  111. unsigned int getFrameBufferID() const noexcept { return 0; }
  112. void triggerRepaint()
  113. {
  114. if (context != nullptr)
  115. context->triggerRepaint();
  116. }
  117. struct Locker
  118. {
  119. explicit Locker (NativeContext& ctx) : lock (ctx.mutex) {}
  120. const ScopedLock lock;
  121. };
  122. HWND getNativeHandle()
  123. {
  124. if (nativeWindow != nullptr)
  125. return (HWND) nativeWindow->getNativeHandle();
  126. return nullptr;
  127. }
  128. private:
  129. //==============================================================================
  130. static void initialiseWGLExtensions (HDC dcIn)
  131. {
  132. static bool initialised = false;
  133. if (initialised)
  134. return;
  135. initialised = true;
  136. const auto dummyContext = wglCreateContext (dcIn);
  137. wglMakeCurrent (dcIn, dummyContext);
  138. #define JUCE_INIT_WGL_FUNCTION(name) name = (type_ ## name) OpenGLHelpers::getExtensionFunction (#name);
  139. JUCE_INIT_WGL_FUNCTION (wglChoosePixelFormatARB)
  140. JUCE_INIT_WGL_FUNCTION (wglSwapIntervalEXT)
  141. JUCE_INIT_WGL_FUNCTION (wglGetSwapIntervalEXT)
  142. JUCE_INIT_WGL_FUNCTION (wglCreateContextAttribsARB)
  143. #undef JUCE_INIT_WGL_FUNCTION
  144. wglMakeCurrent (nullptr, nullptr);
  145. wglDeleteContext (dummyContext);
  146. }
  147. static void initialisePixelFormatDescriptor (PIXELFORMATDESCRIPTOR& pfd, const OpenGLPixelFormat& pixelFormat)
  148. {
  149. zerostruct (pfd);
  150. pfd.nSize = sizeof (pfd);
  151. pfd.nVersion = 1;
  152. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  153. pfd.iPixelType = PFD_TYPE_RGBA;
  154. pfd.iLayerType = PFD_MAIN_PLANE;
  155. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  156. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  157. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  158. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  159. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  160. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  161. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  162. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  163. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  164. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  165. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  166. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  167. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  168. }
  169. static HGLRC createRenderContext (OpenGLVersion version, HDC dcIn)
  170. {
  171. const auto components = [&]() -> Optional<Version>
  172. {
  173. switch (version)
  174. {
  175. case OpenGLVersion::openGL3_2: return Version { 3, 2 };
  176. case OpenGLVersion::openGL4_1: return Version { 4, 1 };
  177. case OpenGLVersion::openGL4_3: return Version { 4, 3 };
  178. case OpenGLVersion::defaultGLVersion: break;
  179. }
  180. return {};
  181. }();
  182. if (components.hasValue() && wglCreateContextAttribsARB != nullptr)
  183. {
  184. #if JUCE_DEBUG
  185. constexpr auto contextFlags = WGL_CONTEXT_DEBUG_BIT_ARB;
  186. constexpr auto noErrorChecking = GL_FALSE;
  187. #else
  188. constexpr auto contextFlags = 0;
  189. constexpr auto noErrorChecking = GL_TRUE;
  190. #endif
  191. const int attribs[] =
  192. {
  193. WGL_CONTEXT_MAJOR_VERSION_ARB, components->major,
  194. WGL_CONTEXT_MINOR_VERSION_ARB, components->minor,
  195. WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
  196. WGL_CONTEXT_FLAGS_ARB, contextFlags,
  197. WGL_CONTEXT_OPENGL_NO_ERROR_ARB, noErrorChecking,
  198. 0
  199. };
  200. const auto c = wglCreateContextAttribsARB (dcIn, nullptr, attribs);
  201. if (c != nullptr)
  202. return c;
  203. }
  204. return wglCreateContext (dcIn);
  205. }
  206. //==============================================================================
  207. struct DummyComponent : public Component
  208. {
  209. DummyComponent (NativeContext& c) : context (c) {}
  210. // The windowing code will call this when a paint callback happens
  211. void handleCommandMessage (int) override { context.triggerRepaint(); }
  212. NativeContext& context;
  213. };
  214. //==============================================================================
  215. void nativeScaleFactorChanged (double newScaleFactor) override
  216. {
  217. if (approximatelyEqual (newScaleFactor, nativeScaleFactor)
  218. || safeComponent == nullptr)
  219. return;
  220. if (auto* peer = safeComponent->getTopLevelComponent()->getPeer())
  221. {
  222. nativeScaleFactor = newScaleFactor;
  223. updateWindowPosition (peer->getAreaCoveredBy (*safeComponent));
  224. }
  225. }
  226. void createNativeWindow (Component& component)
  227. {
  228. auto* topComp = component.getTopLevelComponent();
  229. {
  230. auto* parentHWND = topComp->getWindowHandle();
  231. ScopedThreadDPIAwarenessSetter setter { parentHWND };
  232. nativeWindow.reset (createNonRepaintingEmbeddedWindowsPeer (*dummyComponent, parentHWND));
  233. }
  234. if (auto* peer = topComp->getPeer())
  235. {
  236. safeComponent = Component::SafePointer<Component> (&component);
  237. nativeScaleFactor = peer->getPlatformScaleFactor();
  238. updateWindowPosition (peer->getAreaCoveredBy (component));
  239. peer->addScaleFactorListener (this);
  240. }
  241. nativeWindow->setVisible (true);
  242. dc = std::unique_ptr<std::remove_pointer_t<HDC>, DeviceContextDeleter> { GetDC ((HWND) nativeWindow->getNativeHandle()),
  243. DeviceContextDeleter { (HWND) nativeWindow->getNativeHandle() } };
  244. }
  245. int wglChoosePixelFormatExtension (const OpenGLPixelFormat& pixelFormat) const
  246. {
  247. int format = 0;
  248. if (wglChoosePixelFormatARB != nullptr)
  249. {
  250. int atts[64];
  251. int n = 0;
  252. atts[n++] = WGL_DRAW_TO_WINDOW_ARB; atts[n++] = GL_TRUE;
  253. atts[n++] = WGL_SUPPORT_OPENGL_ARB; atts[n++] = GL_TRUE;
  254. atts[n++] = WGL_DOUBLE_BUFFER_ARB; atts[n++] = GL_TRUE;
  255. atts[n++] = WGL_PIXEL_TYPE_ARB; atts[n++] = WGL_TYPE_RGBA_ARB;
  256. atts[n++] = WGL_ACCELERATION_ARB;
  257. atts[n++] = WGL_FULL_ACCELERATION_ARB;
  258. atts[n++] = WGL_COLOR_BITS_ARB; atts[n++] = pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits;
  259. atts[n++] = WGL_RED_BITS_ARB; atts[n++] = pixelFormat.redBits;
  260. atts[n++] = WGL_GREEN_BITS_ARB; atts[n++] = pixelFormat.greenBits;
  261. atts[n++] = WGL_BLUE_BITS_ARB; atts[n++] = pixelFormat.blueBits;
  262. atts[n++] = WGL_ALPHA_BITS_ARB; atts[n++] = pixelFormat.alphaBits;
  263. atts[n++] = WGL_DEPTH_BITS_ARB; atts[n++] = pixelFormat.depthBufferBits;
  264. atts[n++] = WGL_STENCIL_BITS_ARB; atts[n++] = pixelFormat.stencilBufferBits;
  265. atts[n++] = WGL_ACCUM_RED_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferRedBits;
  266. atts[n++] = WGL_ACCUM_GREEN_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferGreenBits;
  267. atts[n++] = WGL_ACCUM_BLUE_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferBlueBits;
  268. atts[n++] = WGL_ACCUM_ALPHA_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferAlphaBits;
  269. if (pixelFormat.multisamplingLevel > 0
  270. && OpenGLHelpers::isExtensionSupported ("GL_ARB_multisample"))
  271. {
  272. atts[n++] = WGL_SAMPLE_BUFFERS_ARB;
  273. atts[n++] = 1;
  274. atts[n++] = WGL_SAMPLES_ARB;
  275. atts[n++] = pixelFormat.multisamplingLevel;
  276. }
  277. atts[n++] = 0;
  278. jassert (n <= numElementsInArray (atts));
  279. UINT formatsCount = 0;
  280. wglChoosePixelFormatARB (dc.get(), atts, nullptr, 1, &format, &formatsCount);
  281. }
  282. return format;
  283. }
  284. //==============================================================================
  285. #define JUCE_DECLARE_WGL_EXTENSION_FUNCTION(name, returnType, params) \
  286. typedef returnType (__stdcall *type_ ## name) params; static type_ ## name name;
  287. JUCE_DECLARE_WGL_EXTENSION_FUNCTION (wglChoosePixelFormatARB, BOOL, (HDC, const int*, const FLOAT*, UINT, int*, UINT*))
  288. JUCE_DECLARE_WGL_EXTENSION_FUNCTION (wglSwapIntervalEXT, BOOL, (int))
  289. JUCE_DECLARE_WGL_EXTENSION_FUNCTION (wglGetSwapIntervalEXT, int, ())
  290. JUCE_DECLARE_WGL_EXTENSION_FUNCTION (wglCreateContextAttribsARB, HGLRC, (HDC, HGLRC, const int*))
  291. #undef JUCE_DECLARE_WGL_EXTENSION_FUNCTION
  292. //==============================================================================
  293. struct RenderContextDeleter
  294. {
  295. void operator() (HGLRC ptr) const { wglDeleteContext (ptr); }
  296. };
  297. struct DeviceContextDeleter
  298. {
  299. void operator() (HDC ptr) const { ReleaseDC (hwnd, ptr); }
  300. HWND hwnd;
  301. };
  302. CriticalSection mutex;
  303. std::unique_ptr<DummyComponent> dummyComponent;
  304. std::unique_ptr<ComponentPeer> nativeWindow;
  305. std::unique_ptr<ScopedThreadDPIAwarenessSetter> threadAwarenessSetter;
  306. Component::SafePointer<Component> safeComponent;
  307. std::unique_ptr<std::remove_pointer_t<HGLRC>, RenderContextDeleter> renderContext;
  308. std::unique_ptr<std::remove_pointer_t<HDC>, DeviceContextDeleter> dc;
  309. OpenGLContext* context = nullptr;
  310. double nativeScaleFactor = 1.0;
  311. //==============================================================================
  312. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
  313. };
  314. //==============================================================================
  315. bool OpenGLHelpers::isContextActive()
  316. {
  317. return wglGetCurrentContext() != nullptr;
  318. }
  319. } // namespace juce