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.

1736 lines
55KB

  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. #if JUCE_MAC
  19. #include <juce_gui_basics/native/juce_mac_PerScreenDisplayLinks.h>
  20. #endif
  21. namespace juce
  22. {
  23. #if JUCE_IOS
  24. struct AppInactivityCallback // NB: this is a duplicate of an internal declaration in juce_core
  25. {
  26. virtual ~AppInactivityCallback() {}
  27. virtual void appBecomingInactive() = 0;
  28. };
  29. extern Array<AppInactivityCallback*> appBecomingInactiveCallbacks;
  30. // On iOS, all GL calls will crash when the app is running in the background, so
  31. // this prevents them from happening (which some messy locking behaviour)
  32. struct iOSBackgroundProcessCheck : public AppInactivityCallback
  33. {
  34. iOSBackgroundProcessCheck() { isBackgroundProcess(); appBecomingInactiveCallbacks.add (this); }
  35. ~iOSBackgroundProcessCheck() override { appBecomingInactiveCallbacks.removeAllInstancesOf (this); }
  36. bool isBackgroundProcess()
  37. {
  38. const bool b = Process::isForegroundProcess();
  39. isForeground.set (b ? 1 : 0);
  40. return ! b;
  41. }
  42. void appBecomingInactive() override
  43. {
  44. int counter = 2000;
  45. while (--counter > 0 && isForeground.get() != 0)
  46. Thread::sleep (1);
  47. }
  48. private:
  49. Atomic<int> isForeground;
  50. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (iOSBackgroundProcessCheck)
  51. };
  52. #endif
  53. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  54. extern JUCE_API double getScaleFactorForWindow (HWND);
  55. #endif
  56. static bool contextHasTextureNpotFeature()
  57. {
  58. if (getOpenGLVersion() >= Version (2))
  59. return true;
  60. // If the version is < 2, we can't use the newer extension-checking API
  61. // so we have to use glGetString
  62. const auto* extensionsBegin = glGetString (GL_EXTENSIONS);
  63. if (extensionsBegin == nullptr)
  64. return false;
  65. const auto* extensionsEnd = findNullTerminator (extensionsBegin);
  66. const std::string extensionsString (extensionsBegin, extensionsEnd);
  67. const auto stringTokens = StringArray::fromTokens (extensionsString.c_str(), false);
  68. return stringTokens.contains ("GL_ARB_texture_non_power_of_two");
  69. }
  70. //==============================================================================
  71. class OpenGLContext::CachedImage : public CachedComponentImage
  72. {
  73. template <typename T, typename U>
  74. static constexpr bool isFlagSet (const T& t, const U& u) { return (t & u) != 0; }
  75. struct AreaAndScale
  76. {
  77. Rectangle<int> area;
  78. double scale;
  79. auto tie() const { return std::tie (area, scale); }
  80. auto operator== (const AreaAndScale& other) const { return tie() == other.tie(); }
  81. auto operator!= (const AreaAndScale& other) const { return tie() != other.tie(); }
  82. };
  83. class LockedAreaAndScale
  84. {
  85. public:
  86. auto get() const
  87. {
  88. const ScopedLock lock (mutex);
  89. return data;
  90. }
  91. template <typename Fn>
  92. void set (const AreaAndScale& d, Fn&& ifDifferent)
  93. {
  94. const auto old = [&]
  95. {
  96. const ScopedLock lock (mutex);
  97. return std::exchange (data, d);
  98. }();
  99. if (old != d)
  100. ifDifferent();
  101. }
  102. private:
  103. CriticalSection mutex;
  104. AreaAndScale data { {}, 1.0 };
  105. };
  106. public:
  107. CachedImage (OpenGLContext& c, Component& comp,
  108. const OpenGLPixelFormat& pixFormat, void* contextToShare)
  109. : context (c),
  110. component (comp)
  111. {
  112. nativeContext.reset (new NativeContext (component, pixFormat, contextToShare,
  113. c.useMultisampling, c.versionRequired));
  114. if (nativeContext->createdOk())
  115. context.nativeContext = nativeContext.get();
  116. else
  117. nativeContext.reset();
  118. refreshDisplayLinkConnection();
  119. }
  120. ~CachedImage() override
  121. {
  122. stop();
  123. }
  124. //==============================================================================
  125. void start()
  126. {
  127. if (nativeContext != nullptr)
  128. resume();
  129. }
  130. void stop()
  131. {
  132. // make sure everything has finished executing
  133. state |= StateFlags::pendingDestruction;
  134. if (workQueue.size() > 0)
  135. {
  136. if (! renderThread->contains (this))
  137. resume();
  138. while (workQueue.size() != 0)
  139. Thread::sleep (20);
  140. }
  141. pause();
  142. }
  143. //==============================================================================
  144. void pause()
  145. {
  146. renderThread->remove (this);
  147. if ((state.fetch_and (~StateFlags::initialised) & StateFlags::initialised) == 0)
  148. return;
  149. ScopedContextActivator activator;
  150. activator.activate (context);
  151. if (context.renderer != nullptr)
  152. context.renderer->openGLContextClosing();
  153. if (vertexArrayObject != 0)
  154. context.extensions.glDeleteVertexArrays (1, &vertexArrayObject);
  155. associatedObjectNames.clear();
  156. associatedObjects.clear();
  157. cachedImageFrameBuffer.release();
  158. nativeContext->shutdownOnRenderThread();
  159. }
  160. void resume()
  161. {
  162. renderThread->add (this);
  163. }
  164. //==============================================================================
  165. void paint (Graphics&) override
  166. {
  167. if (MessageManager::getInstance()->isThisTheMessageThread())
  168. {
  169. updateViewportSize();
  170. }
  171. else
  172. {
  173. // If you hit this assertion, it's because paint has been called from a thread other
  174. // than the message thread. This commonly happens when nesting OpenGL contexts, because
  175. // the 'outer' OpenGL renderer will attempt to call paint on the 'inner' context's
  176. // component from the OpenGL thread.
  177. // Nesting OpenGL contexts is not directly supported, however there is a workaround:
  178. // https://forum.juce.com/t/opengl-how-do-3d-with-custom-shaders-and-2d-with-juce-paint-methods-work-together/28026/7
  179. jassertfalse;
  180. }
  181. }
  182. bool invalidateAll() override
  183. {
  184. validArea.clear();
  185. triggerRepaint();
  186. return false;
  187. }
  188. bool invalidate (const Rectangle<int>& area) override
  189. {
  190. validArea.subtract (area.toFloat().transformedBy (transform).getSmallestIntegerContainer());
  191. triggerRepaint();
  192. return false;
  193. }
  194. void releaseResources() override
  195. {
  196. stop();
  197. }
  198. void triggerRepaint()
  199. {
  200. state |= (StateFlags::pendingRender | StateFlags::paintComponents);
  201. renderThread->triggerRepaint();
  202. }
  203. //==============================================================================
  204. bool ensureFrameBufferSize (Rectangle<int> viewportArea)
  205. {
  206. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  207. auto fbW = cachedImageFrameBuffer.getWidth();
  208. auto fbH = cachedImageFrameBuffer.getHeight();
  209. if (fbW != viewportArea.getWidth() || fbH != viewportArea.getHeight() || ! cachedImageFrameBuffer.isValid())
  210. {
  211. if (! cachedImageFrameBuffer.initialise (context, viewportArea.getWidth(), viewportArea.getHeight()))
  212. return false;
  213. validArea.clear();
  214. JUCE_CHECK_OPENGL_ERROR
  215. }
  216. return true;
  217. }
  218. void clearRegionInFrameBuffer (const RectangleList<int>& list)
  219. {
  220. glClearColor (0, 0, 0, 0);
  221. glEnable (GL_SCISSOR_TEST);
  222. auto previousFrameBufferTarget = OpenGLFrameBuffer::getCurrentFrameBufferTarget();
  223. cachedImageFrameBuffer.makeCurrentRenderingTarget();
  224. auto imageH = cachedImageFrameBuffer.getHeight();
  225. for (auto& r : list)
  226. {
  227. glScissor (r.getX(), imageH - r.getBottom(), r.getWidth(), r.getHeight());
  228. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  229. }
  230. glDisable (GL_SCISSOR_TEST);
  231. context.extensions.glBindFramebuffer (GL_FRAMEBUFFER, previousFrameBufferTarget);
  232. JUCE_CHECK_OPENGL_ERROR
  233. }
  234. struct ScopedContextActivator
  235. {
  236. bool activate (OpenGLContext& ctx)
  237. {
  238. if (! active)
  239. active = ctx.makeActive();
  240. return active;
  241. }
  242. ~ScopedContextActivator()
  243. {
  244. if (active)
  245. OpenGLContext::deactivateCurrentContext();
  246. }
  247. private:
  248. bool active = false;
  249. };
  250. enum class RenderStatus
  251. {
  252. nominal,
  253. messageThreadAborted,
  254. noWork,
  255. };
  256. RenderStatus renderFrame (MessageManager::Lock& mmLock)
  257. {
  258. if (! isFlagSet (state, StateFlags::initialised))
  259. {
  260. switch (initialiseOnThread())
  261. {
  262. case InitResult::fatal:
  263. case InitResult::retry: return RenderStatus::noWork;
  264. case InitResult::success: break;
  265. }
  266. }
  267. state |= StateFlags::initialised;
  268. #if JUCE_IOS
  269. if (backgroundProcessCheck.isBackgroundProcess())
  270. return RenderStatus::noWork;
  271. #endif
  272. std::optional<MessageManager::Lock::ScopedTryLockType> scopedLock;
  273. ScopedContextActivator contextActivator;
  274. const auto stateToUse = state.fetch_and (StateFlags::persistent);
  275. #if JUCE_MAC
  276. // On macOS, we use a display link callback to trigger repaints, rather than
  277. // letting them run at full throttle
  278. const auto noAutomaticRepaint = true;
  279. #else
  280. const auto noAutomaticRepaint = ! context.continuousRepaint;
  281. #endif
  282. if (! isFlagSet (stateToUse, StateFlags::pendingRender) && noAutomaticRepaint)
  283. return RenderStatus::noWork;
  284. const auto isUpdating = isFlagSet (stateToUse, StateFlags::paintComponents);
  285. if (context.renderComponents && isUpdating)
  286. {
  287. bool abortScope = false;
  288. // If we early-exit here, we need to restore these flags so that the render is
  289. // attempted again in the next time slice.
  290. const ScopeGuard scope { [&] { if (! abortScope) state |= stateToUse; } };
  291. // This avoids hogging the message thread when doing intensive rendering.
  292. std::this_thread::sleep_until (lastMMLockReleaseTime + std::chrono::milliseconds { 2 });
  293. if (renderThread->isListChanging())
  294. return RenderStatus::messageThreadAborted;
  295. doWorkWhileWaitingForLock (contextActivator);
  296. scopedLock.emplace (mmLock);
  297. // If we can't get the lock here, it's probably because a context has been removed
  298. // on the main thread.
  299. // We return, just in case this renderer needs to be removed from the rendering thread.
  300. // If another renderer is being removed instead, then we should be able to get the lock
  301. // next time round.
  302. if (! scopedLock->isLocked())
  303. return RenderStatus::messageThreadAborted;
  304. abortScope = true;
  305. }
  306. {
  307. NativeContext::Locker locker (*nativeContext);
  308. if (! contextActivator.activate (context))
  309. return RenderStatus::noWork;
  310. JUCE_CHECK_OPENGL_ERROR
  311. doWorkWhileWaitingForLock (contextActivator);
  312. const auto currentAreaAndScale = areaAndScale.get();
  313. const auto viewportArea = currentAreaAndScale.area;
  314. if (context.renderer != nullptr)
  315. {
  316. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  317. context.currentRenderScale = currentAreaAndScale.scale;
  318. context.renderer->renderOpenGL();
  319. clearGLError();
  320. bindVertexArray();
  321. }
  322. if (context.renderComponents)
  323. {
  324. if (isUpdating)
  325. {
  326. paintComponent (currentAreaAndScale);
  327. if (! isFlagSet (state, StateFlags::initialised))
  328. return RenderStatus::noWork;
  329. scopedLock.reset();
  330. lastMMLockReleaseTime = std::chrono::steady_clock::now();
  331. }
  332. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  333. drawComponentBuffer();
  334. }
  335. }
  336. bufferSwapper.swap();
  337. return RenderStatus::nominal;
  338. }
  339. void updateViewportSize()
  340. {
  341. JUCE_ASSERT_MESSAGE_THREAD
  342. if (auto* peer = component.getPeer())
  343. {
  344. #if JUCE_MAC
  345. updateScreen();
  346. const auto displayScale = Desktop::getInstance().getGlobalScaleFactor() * [this]
  347. {
  348. if (auto* view = getCurrentView())
  349. {
  350. if ([view respondsToSelector: @selector (backingScaleFactor)])
  351. return [(id) view backingScaleFactor];
  352. if (auto* window = [view window])
  353. return [window backingScaleFactor];
  354. }
  355. return areaAndScale.get().scale;
  356. }();
  357. #else
  358. const auto displayScale = Desktop::getInstance().getDisplays()
  359. .getDisplayForRect (component.getTopLevelComponent()
  360. ->getScreenBounds())
  361. ->scale;
  362. #endif
  363. const auto localBounds = component.getLocalBounds();
  364. const auto newArea = peer->getComponent().getLocalArea (&component, localBounds).withZeroOrigin() * displayScale;
  365. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  366. // Some hosts (Pro Tools 2022.7) do not take the current DPI into account when sizing
  367. // plugin editor windows. Instead of querying the OS for the DPI of the editor window,
  368. // we approximate based on the physical size of the window that was actually provided
  369. // for the context to draw into. This may break if the OpenGL context's component is
  370. // scaled differently in its width and height - but in this case, a single scale factor
  371. // isn't that helpful anyway.
  372. const auto newScale = (float) newArea.getWidth() / (float) localBounds.getWidth();
  373. #else
  374. const auto newScale = (float) displayScale;
  375. #endif
  376. areaAndScale.set ({ newArea, newScale }, [&]
  377. {
  378. // Transform is only accessed when the message manager is locked
  379. transform = AffineTransform::scale ((float) newArea.getWidth() / (float) localBounds.getWidth(),
  380. (float) newArea.getHeight() / (float) localBounds.getHeight());
  381. nativeContext->updateWindowPosition (peer->getAreaCoveredBy (component));
  382. invalidateAll();
  383. });
  384. }
  385. }
  386. void bindVertexArray() noexcept
  387. {
  388. if (shouldUseCustomVAO())
  389. if (vertexArrayObject != 0)
  390. context.extensions.glBindVertexArray (vertexArrayObject);
  391. }
  392. void checkViewportBounds()
  393. {
  394. auto screenBounds = component.getTopLevelComponent()->getScreenBounds();
  395. if (lastScreenBounds != screenBounds)
  396. {
  397. updateViewportSize();
  398. lastScreenBounds = screenBounds;
  399. }
  400. }
  401. void paintComponent (const AreaAndScale& currentAreaAndScale)
  402. {
  403. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  404. // you mustn't set your own cached image object when attaching a GL context!
  405. jassert (get (component) == this);
  406. if (! ensureFrameBufferSize (currentAreaAndScale.area))
  407. return;
  408. RectangleList<int> invalid (currentAreaAndScale.area);
  409. invalid.subtract (validArea);
  410. validArea = currentAreaAndScale.area;
  411. if (! invalid.isEmpty())
  412. {
  413. clearRegionInFrameBuffer (invalid);
  414. {
  415. std::unique_ptr<LowLevelGraphicsContext> g (createOpenGLGraphicsContext (context, cachedImageFrameBuffer));
  416. g->clipToRectangleList (invalid);
  417. g->addTransform (transform);
  418. paintOwner (*g);
  419. JUCE_CHECK_OPENGL_ERROR
  420. }
  421. }
  422. JUCE_CHECK_OPENGL_ERROR
  423. }
  424. void drawComponentBuffer()
  425. {
  426. if (contextRequiresTexture2DEnableDisable())
  427. glEnable (GL_TEXTURE_2D);
  428. #if JUCE_WINDOWS
  429. // some stupidly old drivers are missing this function, so try to at least avoid a crash here,
  430. // but if you hit this assertion you may want to have your own version check before using the
  431. // component rendering stuff on such old drivers.
  432. jassert (context.extensions.glActiveTexture != nullptr);
  433. if (context.extensions.glActiveTexture != nullptr)
  434. #endif
  435. {
  436. context.extensions.glActiveTexture (GL_TEXTURE0);
  437. }
  438. glBindTexture (GL_TEXTURE_2D, cachedImageFrameBuffer.getTextureID());
  439. bindVertexArray();
  440. const Rectangle<int> cacheBounds (cachedImageFrameBuffer.getWidth(), cachedImageFrameBuffer.getHeight());
  441. context.copyTexture (cacheBounds, cacheBounds, cacheBounds.getWidth(), cacheBounds.getHeight(), false);
  442. glBindTexture (GL_TEXTURE_2D, 0);
  443. JUCE_CHECK_OPENGL_ERROR
  444. }
  445. void paintOwner (LowLevelGraphicsContext& llgc)
  446. {
  447. Graphics g (llgc);
  448. #if JUCE_ENABLE_REPAINT_DEBUGGING
  449. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  450. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  451. #endif
  452. {
  453. g.saveState();
  454. }
  455. #endif
  456. JUCE_TRY
  457. {
  458. component.paintEntireComponent (g, false);
  459. }
  460. JUCE_CATCH_EXCEPTION
  461. #if JUCE_ENABLE_REPAINT_DEBUGGING
  462. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  463. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  464. #endif
  465. {
  466. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  467. // clearly when things are being repainted.
  468. g.restoreState();
  469. static Random rng;
  470. g.fillAll (Colour ((uint8) rng.nextInt (255),
  471. (uint8) rng.nextInt (255),
  472. (uint8) rng.nextInt (255),
  473. (uint8) 0x50));
  474. }
  475. #endif
  476. }
  477. void handleResize()
  478. {
  479. updateViewportSize();
  480. #if JUCE_MAC
  481. if (isFlagSet (state, StateFlags::initialised))
  482. {
  483. [nativeContext->view update];
  484. // We're already on the message thread, no need to lock it again.
  485. MessageManager::Lock mml;
  486. renderFrame (mml);
  487. }
  488. #endif
  489. }
  490. //==============================================================================
  491. InitResult initialiseOnThread()
  492. {
  493. // On android, this can get called twice, so drop any previous state.
  494. associatedObjectNames.clear();
  495. associatedObjects.clear();
  496. cachedImageFrameBuffer.release();
  497. context.makeActive();
  498. if (const auto nativeResult = nativeContext->initialiseOnRenderThread (context); nativeResult != InitResult::success)
  499. return nativeResult;
  500. #if JUCE_ANDROID
  501. // On android the context may be created in initialiseOnRenderThread
  502. // and we therefore need to call makeActive again
  503. context.makeActive();
  504. #endif
  505. gl::loadFunctions();
  506. if (shouldUseCustomVAO())
  507. {
  508. context.extensions.glGenVertexArrays (1, &vertexArrayObject);
  509. bindVertexArray();
  510. }
  511. #if JUCE_DEBUG
  512. if (getOpenGLVersion() >= Version { 4, 3 } && glDebugMessageCallback != nullptr)
  513. {
  514. glEnable (GL_DEBUG_OUTPUT);
  515. glDebugMessageCallback ([] (GLenum, GLenum type, GLuint, GLenum severity, GLsizei, const GLchar* message, const void*)
  516. {
  517. // This may reiterate issues that are also flagged by JUCE_CHECK_OPENGL_ERROR.
  518. // The advantage of this callback is that it will catch *all* errors, even if we
  519. // forget to check manually.
  520. DBG ("OpenGL DBG message: " << message);
  521. jassertquiet (type != GL_DEBUG_TYPE_ERROR && severity != GL_DEBUG_SEVERITY_HIGH);
  522. }, nullptr);
  523. }
  524. #endif
  525. const auto currentViewportArea = areaAndScale.get().area;
  526. glViewport (0, 0, currentViewportArea.getWidth(), currentViewportArea.getHeight());
  527. nativeContext->setSwapInterval (1);
  528. #if ! JUCE_OPENGL_ES
  529. JUCE_CHECK_OPENGL_ERROR
  530. shadersAvailable = OpenGLShaderProgram::getLanguageVersion() > 0;
  531. clearGLError();
  532. #endif
  533. textureNpotSupported = contextHasTextureNpotFeature();
  534. if (context.renderer != nullptr)
  535. context.renderer->newOpenGLContextCreated();
  536. return InitResult::success;
  537. }
  538. /* Returns true if the context requires a non-zero vertex array object (VAO) to be bound.
  539. If the context is a compatibility context, we can just pretend that VAOs don't exist,
  540. and use the default VAO all the time instead. This provides a more consistent experience
  541. in user code, which might make calls (like glVertexPointer()) that only work when VAO 0 is
  542. bound in OpenGL 3.2+.
  543. */
  544. bool shouldUseCustomVAO() const
  545. {
  546. #if JUCE_OPENGL_ES
  547. return false;
  548. #else
  549. clearGLError();
  550. GLint mask = 0;
  551. glGetIntegerv (GL_CONTEXT_PROFILE_MASK, &mask);
  552. // The context isn't aware of the profile mask, so it pre-dates the core profile
  553. if (glGetError() == GL_INVALID_ENUM)
  554. return false;
  555. // Also assumes a compatibility profile if the mask is completely empty for some reason
  556. return (mask & (GLint) GL_CONTEXT_CORE_PROFILE_BIT) != 0;
  557. #endif
  558. }
  559. //==============================================================================
  560. struct BlockingWorker : public OpenGLContext::AsyncWorker
  561. {
  562. BlockingWorker (OpenGLContext::AsyncWorker::Ptr && workerToUse)
  563. : originalWorker (std::move (workerToUse))
  564. {}
  565. void operator() (OpenGLContext& calleeContext)
  566. {
  567. if (originalWorker != nullptr)
  568. (*originalWorker) (calleeContext);
  569. finishedSignal.signal();
  570. }
  571. void block() noexcept { finishedSignal.wait(); }
  572. OpenGLContext::AsyncWorker::Ptr originalWorker;
  573. WaitableEvent finishedSignal;
  574. };
  575. void doWorkWhileWaitingForLock (ScopedContextActivator& contextActivator)
  576. {
  577. while (const auto work = workQueue.removeAndReturn (0))
  578. {
  579. if (renderThread->isListChanging() || ! contextActivator.activate (context))
  580. break;
  581. NativeContext::Locker locker (*nativeContext);
  582. (*work) (context);
  583. clearGLError();
  584. }
  585. }
  586. void execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock)
  587. {
  588. if (! isFlagSet (state, StateFlags::pendingDestruction))
  589. {
  590. if (shouldBlock)
  591. {
  592. auto blocker = new BlockingWorker (std::move (workerToUse));
  593. OpenGLContext::AsyncWorker::Ptr worker (*blocker);
  594. workQueue.add (worker);
  595. renderThread->abortLock();
  596. context.triggerRepaint();
  597. blocker->block();
  598. }
  599. else
  600. {
  601. workQueue.add (std::move (workerToUse));
  602. renderThread->abortLock();
  603. context.triggerRepaint();
  604. }
  605. }
  606. else
  607. {
  608. jassertfalse; // you called execute AFTER you detached your OpenGLContext
  609. }
  610. }
  611. //==============================================================================
  612. static CachedImage* get (Component& c) noexcept
  613. {
  614. return dynamic_cast<CachedImage*> (c.getCachedComponentImage());
  615. }
  616. class RenderThread
  617. {
  618. public:
  619. RenderThread() = default;
  620. ~RenderThread()
  621. {
  622. flags.setDestructing();
  623. thread.join();
  624. }
  625. void add (CachedImage* x)
  626. {
  627. const std::scoped_lock lock { listMutex };
  628. images.push_back (x);
  629. }
  630. void remove (CachedImage* x)
  631. {
  632. JUCE_ASSERT_MESSAGE_THREAD;
  633. flags.setSafe (false);
  634. abortLock();
  635. {
  636. const std::scoped_lock lock { callbackMutex, listMutex };
  637. images.remove (x);
  638. }
  639. flags.setSafe (true);
  640. }
  641. bool contains (CachedImage* x)
  642. {
  643. const std::scoped_lock lock { listMutex };
  644. return std::find (images.cbegin(), images.cend(), x) != images.cend();
  645. }
  646. void triggerRepaint() { flags.setRenderRequested(); }
  647. void abortLock() { messageManagerLock.abort(); }
  648. bool isListChanging() { return ! flags.isSafe(); }
  649. private:
  650. RenderStatus renderAll()
  651. {
  652. auto result = RenderStatus::noWork;
  653. const std::scoped_lock lock { callbackMutex, listMutex };
  654. for (auto* x : images)
  655. {
  656. listMutex.unlock();
  657. const ScopeGuard scope { [&] { listMutex.lock(); } };
  658. const auto status = x->renderFrame (messageManagerLock);
  659. switch (status)
  660. {
  661. case RenderStatus::noWork: break;
  662. case RenderStatus::nominal: result = RenderStatus::nominal; break;
  663. case RenderStatus::messageThreadAborted: return RenderStatus::messageThreadAborted;
  664. }
  665. }
  666. return result;
  667. }
  668. /* Allows the main thread to communicate changes to the render thread.
  669. When the render thread needs to change in some way (asked to resume rendering,
  670. a renderer is added/removed, or the thread needs to stop prior to destruction),
  671. the main thread can set the appropriate flag on this structure. The render thread
  672. will call waitForWork() repeatedly, pausing when the render thread has no work to do,
  673. and resuming when requested by the main thread.
  674. */
  675. class Flags
  676. {
  677. public:
  678. void setDestructing() { update ([] (auto& f) { f |= destructorCalled; }); }
  679. void setRenderRequested() { update ([] (auto& f) { f |= renderRequested; }); }
  680. void setSafe (const bool safe)
  681. {
  682. update ([safe] (auto& f)
  683. {
  684. if (safe)
  685. f |= listSafe;
  686. else
  687. f &= ~listSafe;
  688. });
  689. }
  690. bool isSafe()
  691. {
  692. const std::scoped_lock lock { mutex };
  693. return (flags & listSafe) != 0;
  694. }
  695. /* Blocks until the 'safe' flag is set, and at least one other flag is set.
  696. After returning, the renderRequested flag will be unset.
  697. Returns true if rendering should continue.
  698. */
  699. bool waitForWork (bool requestRender)
  700. {
  701. std::unique_lock lock { mutex };
  702. flags |= (requestRender ? renderRequested : 0);
  703. condvar.wait (lock, [this] { return flags > listSafe; });
  704. flags &= ~renderRequested;
  705. return ((flags & destructorCalled) == 0);
  706. }
  707. private:
  708. template <typename Fn>
  709. void update (Fn fn)
  710. {
  711. {
  712. const std::scoped_lock lock { mutex };
  713. fn (flags);
  714. }
  715. condvar.notify_one();
  716. }
  717. enum
  718. {
  719. renderRequested = 1 << 0,
  720. destructorCalled = 1 << 1,
  721. listSafe = 1 << 2
  722. };
  723. std::mutex mutex;
  724. std::condition_variable condvar;
  725. int flags = listSafe;
  726. };
  727. MessageManager::Lock messageManagerLock;
  728. std::mutex listMutex, callbackMutex;
  729. std::list<CachedImage*> images;
  730. Flags flags;
  731. std::thread thread { [this]
  732. {
  733. Thread::setCurrentThreadName ("OpenGL Renderer");
  734. while (flags.waitForWork (renderAll() != RenderStatus::noWork)) {}
  735. } };
  736. };
  737. void refreshDisplayLinkConnection()
  738. {
  739. #if JUCE_MAC
  740. if (context.continuousRepaint)
  741. {
  742. connection.emplace (sharedDisplayLinks->registerFactory ([this] (CGDirectDisplayID display)
  743. {
  744. return [this, display]
  745. {
  746. if (auto* view = nativeContext->getNSView())
  747. if (auto* window = [view window])
  748. if (auto* screen = [window screen])
  749. if (display == ScopedDisplayLink::getDisplayIdForScreen (screen))
  750. triggerRepaint();
  751. };
  752. }));
  753. }
  754. else
  755. {
  756. connection.reset();
  757. }
  758. #endif
  759. }
  760. //==============================================================================
  761. class BufferSwapper : private AsyncUpdater
  762. {
  763. public:
  764. explicit BufferSwapper (CachedImage& img)
  765. : image (img) {}
  766. ~BufferSwapper() override
  767. {
  768. cancelPendingUpdate();
  769. }
  770. void swap()
  771. {
  772. static const auto swapBuffersOnMainThread = []
  773. {
  774. const auto os = SystemStats::getOperatingSystemType();
  775. if ((os & SystemStats::MacOSX) != 0)
  776. return (os != SystemStats::MacOSX && os < SystemStats::MacOSX_10_14);
  777. return false;
  778. }();
  779. if (swapBuffersOnMainThread && ! MessageManager::getInstance()->isThisTheMessageThread())
  780. triggerAsyncUpdate();
  781. else
  782. image.nativeContext->swapBuffers();
  783. }
  784. private:
  785. void handleAsyncUpdate() override
  786. {
  787. ScopedContextActivator activator;
  788. activator.activate (image.context);
  789. NativeContext::Locker locker (*image.nativeContext);
  790. image.nativeContext->swapBuffers();
  791. }
  792. CachedImage& image;
  793. };
  794. //==============================================================================
  795. friend class NativeContext;
  796. std::unique_ptr<NativeContext> nativeContext;
  797. OpenGLContext& context;
  798. Component& component;
  799. SharedResourcePointer<RenderThread> renderThread;
  800. OpenGLFrameBuffer cachedImageFrameBuffer;
  801. RectangleList<int> validArea;
  802. Rectangle<int> lastScreenBounds;
  803. AffineTransform transform;
  804. GLuint vertexArrayObject = 0;
  805. LockedAreaAndScale areaAndScale;
  806. StringArray associatedObjectNames;
  807. ReferenceCountedArray<ReferenceCountedObject> associatedObjects;
  808. WaitableEvent canPaintNowFlag, finishedPaintingFlag;
  809. #if JUCE_OPENGL_ES
  810. bool shadersAvailable = true;
  811. #else
  812. bool shadersAvailable = false;
  813. #endif
  814. bool textureNpotSupported = false;
  815. std::chrono::steady_clock::time_point lastMMLockReleaseTime{};
  816. BufferSwapper bufferSwapper { *this };
  817. #if JUCE_MAC
  818. NSView* getCurrentView() const
  819. {
  820. JUCE_ASSERT_MESSAGE_THREAD;
  821. if (auto* peer = component.getPeer())
  822. return static_cast<NSView*> (peer->getNativeHandle());
  823. return nullptr;
  824. }
  825. NSWindow* getCurrentWindow() const
  826. {
  827. JUCE_ASSERT_MESSAGE_THREAD;
  828. if (auto* view = getCurrentView())
  829. return [view window];
  830. return nullptr;
  831. }
  832. NSScreen* getCurrentScreen() const
  833. {
  834. JUCE_ASSERT_MESSAGE_THREAD;
  835. if (auto* window = getCurrentWindow())
  836. return [window screen];
  837. return nullptr;
  838. }
  839. void updateScreen()
  840. {
  841. const auto screen = getCurrentScreen();
  842. const auto display = ScopedDisplayLink::getDisplayIdForScreen (screen);
  843. if (lastDisplay.exchange (display) == display)
  844. return;
  845. const auto newRefreshPeriod = sharedDisplayLinks->getNominalVideoRefreshPeriodSForScreen (display);
  846. if (newRefreshPeriod != 0.0 && std::exchange (refreshPeriod, newRefreshPeriod) != newRefreshPeriod)
  847. nativeContext->setNominalVideoRefreshPeriodS (newRefreshPeriod);
  848. updateColourSpace();
  849. }
  850. void updateColourSpace()
  851. {
  852. if (auto* view = nativeContext->getNSView())
  853. if (auto* window = [view window])
  854. [window setColorSpace: [NSColorSpace sRGBColorSpace]];
  855. }
  856. std::atomic<CGDirectDisplayID> lastDisplay { 0 };
  857. double refreshPeriod = 0.0;
  858. FunctionNotificationCenterObserver observer { NSWindowDidChangeScreenNotification,
  859. getCurrentWindow(),
  860. [this] { updateScreen(); } };
  861. // Note: the NSViewComponentPeer also has a SharedResourcePointer<PerScreenDisplayLinks> to
  862. // avoid unnecessarily duplicating display-link threads.
  863. SharedResourcePointer<PerScreenDisplayLinks> sharedDisplayLinks;
  864. // On macOS, rather than letting swapBuffers block as appropriate, we use a display link
  865. // callback to mark the view as needing to repaint.
  866. std::optional<PerScreenDisplayLinks::Connection> connection;
  867. #endif
  868. enum StateFlags
  869. {
  870. pendingRender = 1 << 0,
  871. paintComponents = 1 << 1,
  872. pendingDestruction = 1 << 2,
  873. initialised = 1 << 3,
  874. // Flags that should retain their state after each frame
  875. persistent = initialised | pendingDestruction
  876. };
  877. std::atomic<int> state { 0 };
  878. ReferenceCountedArray<OpenGLContext::AsyncWorker, CriticalSection> workQueue;
  879. #if JUCE_IOS
  880. iOSBackgroundProcessCheck backgroundProcessCheck;
  881. #endif
  882. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedImage)
  883. };
  884. //==============================================================================
  885. class OpenGLContext::Attachment : public ComponentMovementWatcher,
  886. private Timer
  887. {
  888. public:
  889. Attachment (OpenGLContext& c, Component& comp)
  890. : ComponentMovementWatcher (&comp), context (c)
  891. {
  892. if (canBeAttached (comp))
  893. attach();
  894. }
  895. ~Attachment() override
  896. {
  897. detach();
  898. }
  899. void detach()
  900. {
  901. auto& comp = *getComponent();
  902. stop();
  903. comp.setCachedComponentImage (nullptr);
  904. context.nativeContext = nullptr;
  905. }
  906. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) override
  907. {
  908. auto& comp = *getComponent();
  909. if (isAttached (comp) != canBeAttached (comp))
  910. componentVisibilityChanged();
  911. if (comp.getWidth() > 0 && comp.getHeight() > 0
  912. && context.nativeContext != nullptr)
  913. {
  914. if (auto* c = CachedImage::get (comp))
  915. c->handleResize();
  916. if (auto* peer = comp.getTopLevelComponent()->getPeer())
  917. context.nativeContext->updateWindowPosition (peer->getAreaCoveredBy (comp));
  918. }
  919. }
  920. using ComponentMovementWatcher::componentMovedOrResized;
  921. void componentPeerChanged() override
  922. {
  923. detach();
  924. componentVisibilityChanged();
  925. }
  926. void componentVisibilityChanged() override
  927. {
  928. auto& comp = *getComponent();
  929. if (canBeAttached (comp))
  930. {
  931. if (isAttached (comp))
  932. comp.repaint(); // (needed when windows are un-minimised)
  933. else
  934. attach();
  935. }
  936. else
  937. {
  938. detach();
  939. }
  940. }
  941. using ComponentMovementWatcher::componentVisibilityChanged;
  942. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  943. void componentBeingDeleted (Component& c) override
  944. {
  945. /* You must call detach() or delete your OpenGLContext to remove it
  946. from a component BEFORE deleting the component that it is using!
  947. */
  948. jassertfalse;
  949. ComponentMovementWatcher::componentBeingDeleted (c);
  950. }
  951. #endif
  952. private:
  953. OpenGLContext& context;
  954. bool canBeAttached (const Component& comp) noexcept
  955. {
  956. return (! context.overrideCanAttach) && comp.getWidth() > 0 && comp.getHeight() > 0 && isShowingOrMinimised (comp);
  957. }
  958. static bool isShowingOrMinimised (const Component& c)
  959. {
  960. if (! c.isVisible())
  961. return false;
  962. if (auto* p = c.getParentComponent())
  963. return isShowingOrMinimised (*p);
  964. return c.getPeer() != nullptr;
  965. }
  966. static bool isAttached (const Component& comp) noexcept
  967. {
  968. return comp.getCachedComponentImage() != nullptr;
  969. }
  970. void attach()
  971. {
  972. auto& comp = *getComponent();
  973. auto* newCachedImage = new CachedImage (context, comp,
  974. context.openGLPixelFormat,
  975. context.contextToShareWith);
  976. comp.setCachedComponentImage (newCachedImage);
  977. start();
  978. }
  979. void stop()
  980. {
  981. stopTimer();
  982. auto& comp = *getComponent();
  983. #if JUCE_MAC
  984. [[(NSView*) comp.getWindowHandle() window] disableScreenUpdatesUntilFlush];
  985. #endif
  986. if (auto* oldCachedImage = CachedImage::get (comp))
  987. oldCachedImage->stop(); // (must stop this before detaching it from the component)
  988. }
  989. void start()
  990. {
  991. auto& comp = *getComponent();
  992. if (auto* cachedImage = CachedImage::get (comp))
  993. {
  994. cachedImage->start(); // (must wait until this is attached before starting its thread)
  995. cachedImage->updateViewportSize();
  996. startTimer (400);
  997. }
  998. }
  999. void timerCallback() override
  1000. {
  1001. if (auto* cachedImage = CachedImage::get (*getComponent()))
  1002. cachedImage->checkViewportBounds();
  1003. }
  1004. };
  1005. //==============================================================================
  1006. OpenGLContext::OpenGLContext()
  1007. {
  1008. }
  1009. OpenGLContext::~OpenGLContext()
  1010. {
  1011. detach();
  1012. }
  1013. void OpenGLContext::setRenderer (OpenGLRenderer* rendererToUse) noexcept
  1014. {
  1015. // This method must not be called when the context has already been attached!
  1016. // Call it before attaching your context, or use detach() first, before calling this!
  1017. jassert (nativeContext == nullptr);
  1018. renderer = rendererToUse;
  1019. }
  1020. void OpenGLContext::setComponentPaintingEnabled (bool shouldPaintComponent) noexcept
  1021. {
  1022. // This method must not be called when the context has already been attached!
  1023. // Call it before attaching your context, or use detach() first, before calling this!
  1024. jassert (nativeContext == nullptr);
  1025. renderComponents = shouldPaintComponent;
  1026. }
  1027. void OpenGLContext::setContinuousRepainting (bool shouldContinuouslyRepaint) noexcept
  1028. {
  1029. continuousRepaint = shouldContinuouslyRepaint;
  1030. #if JUCE_MAC
  1031. if (auto* component = getTargetComponent())
  1032. {
  1033. detach();
  1034. attachment.reset (new Attachment (*this, *component));
  1035. }
  1036. if (auto* cachedImage = getCachedImage())
  1037. cachedImage->refreshDisplayLinkConnection();
  1038. #endif
  1039. triggerRepaint();
  1040. }
  1041. void OpenGLContext::setPixelFormat (const OpenGLPixelFormat& preferredPixelFormat) noexcept
  1042. {
  1043. // This method must not be called when the context has already been attached!
  1044. // Call it before attaching your context, or use detach() first, before calling this!
  1045. jassert (nativeContext == nullptr);
  1046. openGLPixelFormat = preferredPixelFormat;
  1047. }
  1048. void OpenGLContext::setTextureMagnificationFilter (OpenGLContext::TextureMagnificationFilter magFilterMode) noexcept
  1049. {
  1050. texMagFilter = magFilterMode;
  1051. }
  1052. void OpenGLContext::setNativeSharedContext (void* nativeContextToShareWith) noexcept
  1053. {
  1054. // This method must not be called when the context has already been attached!
  1055. // Call it before attaching your context, or use detach() first, before calling this!
  1056. jassert (nativeContext == nullptr);
  1057. contextToShareWith = nativeContextToShareWith;
  1058. }
  1059. void OpenGLContext::setMultisamplingEnabled (bool b) noexcept
  1060. {
  1061. // This method must not be called when the context has already been attached!
  1062. // Call it before attaching your context, or use detach() first, before calling this!
  1063. jassert (nativeContext == nullptr);
  1064. useMultisampling = b;
  1065. }
  1066. void OpenGLContext::setOpenGLVersionRequired (OpenGLVersion v) noexcept
  1067. {
  1068. versionRequired = v;
  1069. }
  1070. void OpenGLContext::attachTo (Component& component)
  1071. {
  1072. component.repaint();
  1073. if (getTargetComponent() != &component)
  1074. {
  1075. detach();
  1076. attachment.reset (new Attachment (*this, component));
  1077. }
  1078. }
  1079. void OpenGLContext::detach()
  1080. {
  1081. if (auto* a = attachment.get())
  1082. {
  1083. a->detach(); // must detach before nulling our pointer
  1084. attachment.reset();
  1085. }
  1086. nativeContext = nullptr;
  1087. }
  1088. bool OpenGLContext::isAttached() const noexcept
  1089. {
  1090. return nativeContext != nullptr;
  1091. }
  1092. Component* OpenGLContext::getTargetComponent() const noexcept
  1093. {
  1094. return attachment != nullptr ? attachment->getComponent() : nullptr;
  1095. }
  1096. OpenGLContext* OpenGLContext::getContextAttachedTo (Component& c) noexcept
  1097. {
  1098. if (auto* ci = CachedImage::get (c))
  1099. return &(ci->context);
  1100. return nullptr;
  1101. }
  1102. static ThreadLocalValue<OpenGLContext*> currentThreadActiveContext;
  1103. OpenGLContext* OpenGLContext::getCurrentContext()
  1104. {
  1105. return currentThreadActiveContext.get();
  1106. }
  1107. bool OpenGLContext::makeActive() const noexcept
  1108. {
  1109. auto& current = currentThreadActiveContext.get();
  1110. if (nativeContext != nullptr && nativeContext->makeActive())
  1111. {
  1112. current = const_cast<OpenGLContext*> (this);
  1113. return true;
  1114. }
  1115. current = nullptr;
  1116. return false;
  1117. }
  1118. bool OpenGLContext::isActive() const noexcept
  1119. {
  1120. return nativeContext != nullptr && nativeContext->isActive();
  1121. }
  1122. void OpenGLContext::deactivateCurrentContext()
  1123. {
  1124. NativeContext::deactivateCurrentContext();
  1125. currentThreadActiveContext.get() = nullptr;
  1126. }
  1127. void OpenGLContext::triggerRepaint()
  1128. {
  1129. if (auto* cachedImage = getCachedImage())
  1130. cachedImage->triggerRepaint();
  1131. }
  1132. void OpenGLContext::swapBuffers()
  1133. {
  1134. if (nativeContext != nullptr)
  1135. nativeContext->swapBuffers();
  1136. }
  1137. unsigned int OpenGLContext::getFrameBufferID() const noexcept
  1138. {
  1139. return nativeContext != nullptr ? nativeContext->getFrameBufferID() : 0;
  1140. }
  1141. bool OpenGLContext::setSwapInterval (int numFramesPerSwap)
  1142. {
  1143. return nativeContext != nullptr && nativeContext->setSwapInterval (numFramesPerSwap);
  1144. }
  1145. int OpenGLContext::getSwapInterval() const
  1146. {
  1147. return nativeContext != nullptr ? nativeContext->getSwapInterval() : 0;
  1148. }
  1149. void* OpenGLContext::getRawContext() const noexcept
  1150. {
  1151. return nativeContext != nullptr ? nativeContext->getRawContext() : nullptr;
  1152. }
  1153. OpenGLContext::CachedImage* OpenGLContext::getCachedImage() const noexcept
  1154. {
  1155. if (auto* comp = getTargetComponent())
  1156. return CachedImage::get (*comp);
  1157. return nullptr;
  1158. }
  1159. bool OpenGLContext::areShadersAvailable() const
  1160. {
  1161. auto* c = getCachedImage();
  1162. return c != nullptr && c->shadersAvailable;
  1163. }
  1164. bool OpenGLContext::isTextureNpotSupported() const
  1165. {
  1166. auto* c = getCachedImage();
  1167. return c != nullptr && c->textureNpotSupported;
  1168. }
  1169. ReferenceCountedObject* OpenGLContext::getAssociatedObject (const char* name) const
  1170. {
  1171. jassert (name != nullptr);
  1172. auto* c = getCachedImage();
  1173. // This method must only be called from an openGL rendering callback.
  1174. jassert (c != nullptr && nativeContext != nullptr);
  1175. jassert (getCurrentContext() != nullptr);
  1176. auto index = c->associatedObjectNames.indexOf (name);
  1177. return index >= 0 ? c->associatedObjects.getUnchecked (index).get() : nullptr;
  1178. }
  1179. void OpenGLContext::setAssociatedObject (const char* name, ReferenceCountedObject* newObject)
  1180. {
  1181. jassert (name != nullptr);
  1182. if (auto* c = getCachedImage())
  1183. {
  1184. // This method must only be called from an openGL rendering callback.
  1185. jassert (nativeContext != nullptr);
  1186. jassert (getCurrentContext() != nullptr);
  1187. const int index = c->associatedObjectNames.indexOf (name);
  1188. if (index >= 0)
  1189. {
  1190. if (newObject != nullptr)
  1191. {
  1192. c->associatedObjects.set (index, newObject);
  1193. }
  1194. else
  1195. {
  1196. c->associatedObjectNames.remove (index);
  1197. c->associatedObjects.remove (index);
  1198. }
  1199. }
  1200. else if (newObject != nullptr)
  1201. {
  1202. c->associatedObjectNames.add (name);
  1203. c->associatedObjects.add (newObject);
  1204. }
  1205. }
  1206. }
  1207. void OpenGLContext::setImageCacheSize (size_t newSize) noexcept { imageCacheMaxSize = newSize; }
  1208. size_t OpenGLContext::getImageCacheSize() const noexcept { return imageCacheMaxSize; }
  1209. void OpenGLContext::execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock)
  1210. {
  1211. if (auto* c = getCachedImage())
  1212. c->execute (std::move (workerToUse), shouldBlock);
  1213. else
  1214. jassertfalse; // You must have attached the context to a component
  1215. }
  1216. //==============================================================================
  1217. struct DepthTestDisabler
  1218. {
  1219. DepthTestDisabler() noexcept
  1220. {
  1221. glGetBooleanv (GL_DEPTH_TEST, &wasEnabled);
  1222. if (wasEnabled)
  1223. glDisable (GL_DEPTH_TEST);
  1224. }
  1225. ~DepthTestDisabler() noexcept
  1226. {
  1227. if (wasEnabled)
  1228. glEnable (GL_DEPTH_TEST);
  1229. }
  1230. GLboolean wasEnabled;
  1231. };
  1232. //==============================================================================
  1233. void OpenGLContext::copyTexture (const Rectangle<int>& targetClipArea,
  1234. const Rectangle<int>& anchorPosAndTextureSize,
  1235. const int contextWidth, const int contextHeight,
  1236. bool flippedVertically)
  1237. {
  1238. if (contextWidth <= 0 || contextHeight <= 0)
  1239. return;
  1240. JUCE_CHECK_OPENGL_ERROR
  1241. glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  1242. glEnable (GL_BLEND);
  1243. DepthTestDisabler depthDisabler;
  1244. if (areShadersAvailable())
  1245. {
  1246. struct OverlayShaderProgram : public ReferenceCountedObject
  1247. {
  1248. OverlayShaderProgram (OpenGLContext& context)
  1249. : program (context), params (program)
  1250. {}
  1251. static const OverlayShaderProgram& select (OpenGLContext& context)
  1252. {
  1253. static const char programValueID[] = "juceGLComponentOverlayShader";
  1254. OverlayShaderProgram* program = static_cast<OverlayShaderProgram*> (context.getAssociatedObject (programValueID));
  1255. if (program == nullptr)
  1256. {
  1257. program = new OverlayShaderProgram (context);
  1258. context.setAssociatedObject (programValueID, program);
  1259. }
  1260. program->program.use();
  1261. return *program;
  1262. }
  1263. struct BuiltProgram : public OpenGLShaderProgram
  1264. {
  1265. explicit BuiltProgram (OpenGLContext& ctx)
  1266. : OpenGLShaderProgram (ctx)
  1267. {
  1268. addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (
  1269. "attribute " JUCE_HIGHP " vec2 position;"
  1270. "uniform " JUCE_HIGHP " vec2 screenSize;"
  1271. "uniform " JUCE_HIGHP " float textureBounds[4];"
  1272. "uniform " JUCE_HIGHP " vec2 vOffsetAndScale;"
  1273. "varying " JUCE_HIGHP " vec2 texturePos;"
  1274. "void main()"
  1275. "{"
  1276. JUCE_HIGHP " vec2 scaled = position / (0.5 * screenSize.xy);"
  1277. "gl_Position = vec4 (scaled.x - 1.0, 1.0 - scaled.y, 0, 1.0);"
  1278. "texturePos = (position - vec2 (textureBounds[0], textureBounds[1])) / vec2 (textureBounds[2], textureBounds[3]);"
  1279. "texturePos = vec2 (texturePos.x, vOffsetAndScale.x + vOffsetAndScale.y * texturePos.y);"
  1280. "}"));
  1281. addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (
  1282. "uniform sampler2D imageTexture;"
  1283. "varying " JUCE_HIGHP " vec2 texturePos;"
  1284. "void main()"
  1285. "{"
  1286. "gl_FragColor = texture2D (imageTexture, texturePos);"
  1287. "}"));
  1288. link();
  1289. }
  1290. };
  1291. struct Params
  1292. {
  1293. Params (OpenGLShaderProgram& prog)
  1294. : positionAttribute (prog, "position"),
  1295. screenSize (prog, "screenSize"),
  1296. imageTexture (prog, "imageTexture"),
  1297. textureBounds (prog, "textureBounds"),
  1298. vOffsetAndScale (prog, "vOffsetAndScale")
  1299. {}
  1300. void set (const float targetWidth, const float targetHeight, const Rectangle<float>& bounds, bool flipVertically) const
  1301. {
  1302. const GLfloat m[] = { bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight() };
  1303. textureBounds.set (m, 4);
  1304. imageTexture.set (0);
  1305. screenSize.set (targetWidth, targetHeight);
  1306. vOffsetAndScale.set (flipVertically ? 0.0f : 1.0f,
  1307. flipVertically ? 1.0f : -1.0f);
  1308. }
  1309. OpenGLShaderProgram::Attribute positionAttribute;
  1310. OpenGLShaderProgram::Uniform screenSize, imageTexture, textureBounds, vOffsetAndScale;
  1311. };
  1312. BuiltProgram program;
  1313. Params params;
  1314. };
  1315. auto left = (GLshort) targetClipArea.getX();
  1316. auto top = (GLshort) targetClipArea.getY();
  1317. auto right = (GLshort) targetClipArea.getRight();
  1318. auto bottom = (GLshort) targetClipArea.getBottom();
  1319. const GLshort vertices[] = { left, bottom, right, bottom, left, top, right, top };
  1320. auto& program = OverlayShaderProgram::select (*this);
  1321. program.params.set ((float) contextWidth, (float) contextHeight, anchorPosAndTextureSize.toFloat(), flippedVertically);
  1322. GLuint vertexBuffer = 0;
  1323. extensions.glGenBuffers (1, &vertexBuffer);
  1324. extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
  1325. extensions.glBufferData (GL_ARRAY_BUFFER, sizeof (vertices), vertices, GL_STATIC_DRAW);
  1326. auto index = (GLuint) program.params.positionAttribute.attributeID;
  1327. extensions.glVertexAttribPointer (index, 2, GL_SHORT, GL_FALSE, 4, nullptr);
  1328. extensions.glEnableVertexAttribArray (index);
  1329. JUCE_CHECK_OPENGL_ERROR
  1330. if (extensions.glCheckFramebufferStatus (GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
  1331. {
  1332. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  1333. extensions.glBindBuffer (GL_ARRAY_BUFFER, 0);
  1334. extensions.glUseProgram (0);
  1335. extensions.glDisableVertexAttribArray (index);
  1336. extensions.glDeleteBuffers (1, &vertexBuffer);
  1337. }
  1338. else
  1339. {
  1340. clearGLError();
  1341. }
  1342. }
  1343. else
  1344. {
  1345. jassert (attachment == nullptr); // Running on an old graphics card!
  1346. }
  1347. JUCE_CHECK_OPENGL_ERROR
  1348. }
  1349. #if JUCE_ANDROID
  1350. void OpenGLContext::NativeContext::surfaceCreated (LocalRef<jobject>)
  1351. {
  1352. {
  1353. const std::lock_guard lock { nativeHandleMutex };
  1354. jassert (hasInitialised);
  1355. // has the context already attached?
  1356. jassert (surface.get() == EGL_NO_SURFACE && context.get() == EGL_NO_CONTEXT);
  1357. const auto window = getNativeWindow();
  1358. if (window == nullptr)
  1359. {
  1360. // failed to get a pointer to the native window so bail out
  1361. jassertfalse;
  1362. return;
  1363. }
  1364. // create the surface
  1365. surface.reset (eglCreateWindowSurface (display, config, window.get(), nullptr));
  1366. jassert (surface.get() != EGL_NO_SURFACE);
  1367. // create the OpenGL context
  1368. EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
  1369. context.reset (eglCreateContext (display, config, EGL_NO_CONTEXT, contextAttribs));
  1370. jassert (context.get() != EGL_NO_CONTEXT);
  1371. }
  1372. if (auto* cached = CachedImage::get (component))
  1373. {
  1374. cached->resume();
  1375. cached->triggerRepaint();
  1376. }
  1377. }
  1378. void OpenGLContext::NativeContext::surfaceDestroyed (LocalRef<jobject>)
  1379. {
  1380. if (auto* cached = CachedImage::get (component))
  1381. cached->pause();
  1382. {
  1383. const std::lock_guard lock { nativeHandleMutex };
  1384. context.reset (EGL_NO_CONTEXT);
  1385. surface.reset (EGL_NO_SURFACE);
  1386. }
  1387. }
  1388. #endif
  1389. } // namespace juce