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.

1320 lines
40KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. #if JUCE_IOS
  16. struct AppInactivityCallback // NB: this is a duplicate of an internal declaration in juce_core
  17. {
  18. virtual ~AppInactivityCallback() {}
  19. virtual void appBecomingInactive() = 0;
  20. };
  21. extern Array<AppInactivityCallback*> appBecomingInactiveCallbacks;
  22. // On iOS, all GL calls will crash when the app is running in the background, so
  23. // this prevents them from happening (which some messy locking behaviour)
  24. struct iOSBackgroundProcessCheck : public AppInactivityCallback
  25. {
  26. iOSBackgroundProcessCheck() { isBackgroundProcess(); appBecomingInactiveCallbacks.add (this); }
  27. ~iOSBackgroundProcessCheck() override { appBecomingInactiveCallbacks.removeAllInstancesOf (this); }
  28. bool isBackgroundProcess()
  29. {
  30. const bool b = Process::isForegroundProcess();
  31. isForeground.set (b ? 1 : 0);
  32. return ! b;
  33. }
  34. void appBecomingInactive() override
  35. {
  36. int counter = 2000;
  37. while (--counter > 0 && isForeground.get() != 0)
  38. Thread::sleep (1);
  39. }
  40. private:
  41. Atomic<int> isForeground;
  42. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (iOSBackgroundProcessCheck)
  43. };
  44. #endif
  45. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  46. extern JUCE_API double getScaleFactorForWindow (HWND);
  47. #endif
  48. //==============================================================================
  49. class OpenGLContext::CachedImage : public CachedComponentImage,
  50. private ThreadPoolJob
  51. {
  52. public:
  53. CachedImage (OpenGLContext& c, Component& comp,
  54. const OpenGLPixelFormat& pixFormat, void* contextToShare)
  55. : ThreadPoolJob ("OpenGL Rendering"),
  56. context (c), component (comp)
  57. {
  58. nativeContext.reset (new NativeContext (component, pixFormat, contextToShare,
  59. c.useMultisampling, c.versionRequired));
  60. if (nativeContext->createdOk())
  61. context.nativeContext = nativeContext.get();
  62. else
  63. nativeContext.reset();
  64. }
  65. ~CachedImage() override
  66. {
  67. stop();
  68. }
  69. //==============================================================================
  70. void start()
  71. {
  72. if (nativeContext != nullptr)
  73. {
  74. renderThread.reset (new ThreadPool (1));
  75. resume();
  76. }
  77. }
  78. void stop()
  79. {
  80. if (renderThread != nullptr)
  81. {
  82. // make sure everything has finished executing
  83. destroying = true;
  84. if (workQueue.size() > 0)
  85. {
  86. if (! renderThread->contains (this))
  87. resume();
  88. while (workQueue.size() != 0)
  89. Thread::sleep (20);
  90. }
  91. pause();
  92. renderThread.reset();
  93. }
  94. hasInitialised = false;
  95. }
  96. //==============================================================================
  97. void pause()
  98. {
  99. signalJobShouldExit();
  100. messageManagerLock.abort();
  101. if (renderThread != nullptr)
  102. {
  103. repaintEvent.signal();
  104. renderThread->removeJob (this, true, -1);
  105. }
  106. }
  107. void resume()
  108. {
  109. if (renderThread != nullptr)
  110. renderThread->addJob (this, false);
  111. }
  112. //==============================================================================
  113. void paint (Graphics&) override
  114. {
  115. updateViewportSize (false);
  116. }
  117. bool invalidateAll() override
  118. {
  119. validArea.clear();
  120. triggerRepaint();
  121. return false;
  122. }
  123. bool invalidate (const Rectangle<int>& area) override
  124. {
  125. validArea.subtract (area.toFloat().transformedBy (transform).getSmallestIntegerContainer());
  126. triggerRepaint();
  127. return false;
  128. }
  129. void releaseResources() override
  130. {
  131. stop();
  132. }
  133. void triggerRepaint()
  134. {
  135. needsUpdate = 1;
  136. repaintEvent.signal();
  137. }
  138. //==============================================================================
  139. bool ensureFrameBufferSize()
  140. {
  141. auto fbW = cachedImageFrameBuffer.getWidth();
  142. auto fbH = cachedImageFrameBuffer.getHeight();
  143. if (fbW != viewportArea.getWidth() || fbH != viewportArea.getHeight() || ! cachedImageFrameBuffer.isValid())
  144. {
  145. if (! cachedImageFrameBuffer.initialise (context, viewportArea.getWidth(), viewportArea.getHeight()))
  146. return false;
  147. validArea.clear();
  148. JUCE_CHECK_OPENGL_ERROR
  149. }
  150. return true;
  151. }
  152. void clearRegionInFrameBuffer (const RectangleList<int>& list)
  153. {
  154. glClearColor (0, 0, 0, 0);
  155. glEnable (GL_SCISSOR_TEST);
  156. auto previousFrameBufferTarget = OpenGLFrameBuffer::getCurrentFrameBufferTarget();
  157. cachedImageFrameBuffer.makeCurrentRenderingTarget();
  158. auto imageH = cachedImageFrameBuffer.getHeight();
  159. for (auto& r : list)
  160. {
  161. glScissor (r.getX(), imageH - r.getBottom(), r.getWidth(), r.getHeight());
  162. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  163. }
  164. glDisable (GL_SCISSOR_TEST);
  165. context.extensions.glBindFramebuffer (GL_FRAMEBUFFER, previousFrameBufferTarget);
  166. JUCE_CHECK_OPENGL_ERROR
  167. }
  168. bool renderFrame()
  169. {
  170. MessageManager::Lock::ScopedTryLockType mmLock (messageManagerLock, false);
  171. auto isUpdatingTestValue = true;
  172. auto isUpdating = needsUpdate.compare_exchange_strong (isUpdatingTestValue, false);
  173. if (context.renderComponents && isUpdating)
  174. {
  175. // This avoids hogging the message thread when doing intensive rendering.
  176. if (lastMMLockReleaseTime + 1 >= Time::getMillisecondCounter())
  177. Thread::sleep (2);
  178. while (! shouldExit())
  179. {
  180. doWorkWhileWaitingForLock (false);
  181. if (mmLock.retryLock())
  182. break;
  183. }
  184. if (shouldExit())
  185. return false;
  186. }
  187. if (! context.makeActive())
  188. return false;
  189. NativeContext::Locker locker (*nativeContext);
  190. JUCE_CHECK_OPENGL_ERROR
  191. doWorkWhileWaitingForLock (true);
  192. if (context.renderer != nullptr)
  193. {
  194. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  195. context.currentRenderScale = scale;
  196. context.renderer->renderOpenGL();
  197. clearGLError();
  198. bindVertexArray();
  199. }
  200. if (context.renderComponents)
  201. {
  202. if (isUpdating)
  203. {
  204. paintComponent();
  205. if (! hasInitialised)
  206. return false;
  207. messageManagerLock.exit();
  208. lastMMLockReleaseTime = Time::getMillisecondCounter();
  209. }
  210. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  211. drawComponentBuffer();
  212. }
  213. context.swapBuffers();
  214. OpenGLContext::deactivateCurrentContext();
  215. return true;
  216. }
  217. void updateViewportSize (bool canTriggerUpdate)
  218. {
  219. if (auto* peer = component.getPeer())
  220. {
  221. auto localBounds = component.getLocalBounds();
  222. auto displayScale = Desktop::getInstance().getDisplays().findDisplayForRect (component.getTopLevelComponent()->getScreenBounds()).scale;
  223. auto newArea = peer->getComponent().getLocalArea (&component, localBounds).withZeroOrigin() * displayScale;
  224. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  225. auto newScale = getScaleFactorForWindow (nativeContext->getNativeHandle());
  226. #else
  227. auto newScale = displayScale;
  228. #endif
  229. if (scale != newScale || viewportArea != newArea)
  230. {
  231. scale = newScale;
  232. viewportArea = newArea;
  233. transform = AffineTransform::scale ((float) newArea.getWidth() / (float) localBounds.getWidth(),
  234. (float) newArea.getHeight() / (float) localBounds.getHeight());
  235. nativeContext->updateWindowPosition (peer->getAreaCoveredBy (component));
  236. if (canTriggerUpdate)
  237. invalidateAll();
  238. }
  239. }
  240. }
  241. void bindVertexArray() noexcept
  242. {
  243. #if JUCE_OPENGL3
  244. if (vertexArrayObject != 0)
  245. context.extensions.glBindVertexArray (vertexArrayObject);
  246. #endif
  247. }
  248. void checkViewportBounds()
  249. {
  250. auto screenBounds = component.getTopLevelComponent()->getScreenBounds();
  251. if (lastScreenBounds != screenBounds)
  252. updateViewportSize (true);
  253. }
  254. void paintComponent()
  255. {
  256. // you mustn't set your own cached image object when attaching a GL context!
  257. jassert (get (component) == this);
  258. if (! ensureFrameBufferSize())
  259. return;
  260. RectangleList<int> invalid (viewportArea);
  261. invalid.subtract (validArea);
  262. validArea = viewportArea;
  263. if (! invalid.isEmpty())
  264. {
  265. clearRegionInFrameBuffer (invalid);
  266. {
  267. std::unique_ptr<LowLevelGraphicsContext> g (createOpenGLGraphicsContext (context, cachedImageFrameBuffer));
  268. g->clipToRectangleList (invalid);
  269. g->addTransform (transform);
  270. paintOwner (*g);
  271. JUCE_CHECK_OPENGL_ERROR
  272. }
  273. if (! context.isActive())
  274. context.makeActive();
  275. }
  276. JUCE_CHECK_OPENGL_ERROR
  277. }
  278. void drawComponentBuffer()
  279. {
  280. #if ! JUCE_ANDROID
  281. glEnable (GL_TEXTURE_2D);
  282. clearGLError();
  283. #endif
  284. #if JUCE_WINDOWS
  285. // some stupidly old drivers are missing this function, so try to at least avoid a crash here,
  286. // but if you hit this assertion you may want to have your own version check before using the
  287. // component rendering stuff on such old drivers.
  288. jassert (context.extensions.glActiveTexture != nullptr);
  289. if (context.extensions.glActiveTexture != nullptr)
  290. #endif
  291. context.extensions.glActiveTexture (GL_TEXTURE0);
  292. glBindTexture (GL_TEXTURE_2D, cachedImageFrameBuffer.getTextureID());
  293. bindVertexArray();
  294. const Rectangle<int> cacheBounds (cachedImageFrameBuffer.getWidth(), cachedImageFrameBuffer.getHeight());
  295. context.copyTexture (cacheBounds, cacheBounds, cacheBounds.getWidth(), cacheBounds.getHeight(), false);
  296. glBindTexture (GL_TEXTURE_2D, 0);
  297. JUCE_CHECK_OPENGL_ERROR
  298. }
  299. void paintOwner (LowLevelGraphicsContext& llgc)
  300. {
  301. Graphics g (llgc);
  302. #if JUCE_ENABLE_REPAINT_DEBUGGING
  303. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  304. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  305. #endif
  306. {
  307. g.saveState();
  308. }
  309. #endif
  310. JUCE_TRY
  311. {
  312. component.paintEntireComponent (g, false);
  313. }
  314. JUCE_CATCH_EXCEPTION
  315. #if JUCE_ENABLE_REPAINT_DEBUGGING
  316. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  317. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  318. #endif
  319. {
  320. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  321. // clearly when things are being repainted.
  322. g.restoreState();
  323. static Random rng;
  324. g.fillAll (Colour ((uint8) rng.nextInt (255),
  325. (uint8) rng.nextInt (255),
  326. (uint8) rng.nextInt (255),
  327. (uint8) 0x50));
  328. }
  329. #endif
  330. }
  331. void handleResize()
  332. {
  333. updateViewportSize (true);
  334. #if JUCE_MAC
  335. if (hasInitialised)
  336. {
  337. [nativeContext->view update];
  338. renderFrame();
  339. }
  340. #endif
  341. }
  342. //==============================================================================
  343. JobStatus runJob() override
  344. {
  345. {
  346. // Allow the message thread to finish setting-up the context before using it..
  347. MessageManager::Lock::ScopedTryLockType mmLock (messageManagerLock, false);
  348. do
  349. {
  350. if (shouldExit())
  351. return ThreadPoolJob::jobHasFinished;
  352. } while (! mmLock.retryLock());
  353. }
  354. if (! initialiseOnThread())
  355. {
  356. hasInitialised = false;
  357. return ThreadPoolJob::jobHasFinished;
  358. }
  359. hasInitialised = true;
  360. while (! shouldExit())
  361. {
  362. #if JUCE_IOS
  363. if (backgroundProcessCheck.isBackgroundProcess())
  364. {
  365. repaintEvent.wait (300);
  366. continue;
  367. }
  368. #endif
  369. if (shouldExit())
  370. break;
  371. #if JUCE_MAC
  372. if (cvDisplayLinkWrapper != nullptr)
  373. repaintEvent.wait (1000);
  374. else
  375. #endif
  376. if (! renderFrame())
  377. repaintEvent.wait (5); // failed to render, so avoid a tight fail-loop.
  378. else if (! context.continuousRepaint && ! shouldExit())
  379. repaintEvent.wait (-1);
  380. }
  381. hasInitialised = false;
  382. context.makeActive();
  383. shutdownOnThread();
  384. OpenGLContext::deactivateCurrentContext();
  385. return ThreadPoolJob::jobHasFinished;
  386. }
  387. bool initialiseOnThread()
  388. {
  389. // On android, this can get called twice, so drop any previous state..
  390. associatedObjectNames.clear();
  391. associatedObjects.clear();
  392. cachedImageFrameBuffer.release();
  393. context.makeActive();
  394. if (! nativeContext->initialiseOnRenderThread (context))
  395. return false;
  396. #if JUCE_ANDROID
  397. // On android the context may be created in initialiseOnRenderThread
  398. // and we therefore need to call makeActive again
  399. context.makeActive();
  400. #endif
  401. context.extensions.initialise();
  402. #if JUCE_OPENGL3
  403. if (OpenGLShaderProgram::getLanguageVersion() > 1.2)
  404. {
  405. context.extensions.glGenVertexArrays (1, &vertexArrayObject);
  406. bindVertexArray();
  407. }
  408. #endif
  409. glViewport (0, 0, component.getWidth(), component.getHeight());
  410. nativeContext->setSwapInterval (1);
  411. #if ! JUCE_OPENGL_ES
  412. JUCE_CHECK_OPENGL_ERROR
  413. shadersAvailable = OpenGLShaderProgram::getLanguageVersion() > 0;
  414. clearGLError();
  415. #endif
  416. if (context.renderer != nullptr)
  417. context.renderer->newOpenGLContextCreated();
  418. #if JUCE_MAC
  419. if (context.continuousRepaint)
  420. cvDisplayLinkWrapper = std::make_unique<CVDisplayLinkWrapper> (this);
  421. #endif
  422. return true;
  423. }
  424. void shutdownOnThread()
  425. {
  426. #if JUCE_MAC
  427. cvDisplayLinkWrapper = nullptr;
  428. #endif
  429. if (context.renderer != nullptr)
  430. context.renderer->openGLContextClosing();
  431. #if JUCE_OPENGL3
  432. if (vertexArrayObject != 0)
  433. context.extensions.glDeleteVertexArrays (1, &vertexArrayObject);
  434. #endif
  435. associatedObjectNames.clear();
  436. associatedObjects.clear();
  437. cachedImageFrameBuffer.release();
  438. nativeContext->shutdownOnRenderThread();
  439. }
  440. //==============================================================================
  441. struct BlockingWorker : public OpenGLContext::AsyncWorker
  442. {
  443. BlockingWorker (OpenGLContext::AsyncWorker::Ptr && workerToUse)
  444. : originalWorker (std::move (workerToUse))
  445. {}
  446. void operator() (OpenGLContext& calleeContext)
  447. {
  448. if (originalWorker != nullptr)
  449. (*originalWorker) (calleeContext);
  450. finishedSignal.signal();
  451. }
  452. void block() noexcept { finishedSignal.wait(); }
  453. OpenGLContext::AsyncWorker::Ptr originalWorker;
  454. WaitableEvent finishedSignal;
  455. };
  456. bool doWorkWhileWaitingForLock (bool contextIsAlreadyActive)
  457. {
  458. bool contextActivated = false;
  459. for (OpenGLContext::AsyncWorker::Ptr work = workQueue.removeAndReturn (0);
  460. work != nullptr && (! shouldExit()); work = workQueue.removeAndReturn (0))
  461. {
  462. if ((! contextActivated) && (! contextIsAlreadyActive))
  463. {
  464. if (! context.makeActive())
  465. break;
  466. contextActivated = true;
  467. }
  468. NativeContext::Locker locker (*nativeContext);
  469. (*work) (context);
  470. clearGLError();
  471. }
  472. if (contextActivated)
  473. OpenGLContext::deactivateCurrentContext();
  474. return shouldExit();
  475. }
  476. void execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock, bool calledFromDestructor = false)
  477. {
  478. if (calledFromDestructor || ! destroying)
  479. {
  480. if (shouldBlock)
  481. {
  482. auto blocker = new BlockingWorker (std::move (workerToUse));
  483. OpenGLContext::AsyncWorker::Ptr worker (*blocker);
  484. workQueue.add (worker);
  485. messageManagerLock.abort();
  486. context.triggerRepaint();
  487. blocker->block();
  488. }
  489. else
  490. {
  491. workQueue.add (std::move (workerToUse));
  492. messageManagerLock.abort();
  493. context.triggerRepaint();
  494. }
  495. }
  496. else
  497. {
  498. jassertfalse; // you called execute AFTER you detached your openglcontext
  499. }
  500. }
  501. //==============================================================================
  502. static CachedImage* get (Component& c) noexcept
  503. {
  504. return dynamic_cast<CachedImage*> (c.getCachedComponentImage());
  505. }
  506. //==============================================================================
  507. friend class NativeContext;
  508. std::unique_ptr<NativeContext> nativeContext;
  509. OpenGLContext& context;
  510. Component& component;
  511. OpenGLFrameBuffer cachedImageFrameBuffer;
  512. RectangleList<int> validArea;
  513. Rectangle<int> viewportArea, lastScreenBounds;
  514. double scale = 1.0;
  515. AffineTransform transform;
  516. #if JUCE_OPENGL3
  517. GLuint vertexArrayObject = 0;
  518. #endif
  519. StringArray associatedObjectNames;
  520. ReferenceCountedArray<ReferenceCountedObject> associatedObjects;
  521. WaitableEvent canPaintNowFlag, finishedPaintingFlag, repaintEvent;
  522. #if JUCE_OPENGL_ES
  523. bool shadersAvailable = true;
  524. #else
  525. bool shadersAvailable = false;
  526. #endif
  527. std::atomic<bool> hasInitialised { false }, needsUpdate { true }, destroying { false };
  528. uint32 lastMMLockReleaseTime = 0;
  529. #if JUCE_MAC
  530. struct CVDisplayLinkWrapper
  531. {
  532. CVDisplayLinkWrapper (CachedImage* im)
  533. {
  534. CVDisplayLinkCreateWithActiveCGDisplays (&displayLink);
  535. CVDisplayLinkSetOutputCallback (displayLink, &displayLinkCallback, im);
  536. CVDisplayLinkStart (displayLink);
  537. }
  538. ~CVDisplayLinkWrapper()
  539. {
  540. CVDisplayLinkStop (displayLink);
  541. CVDisplayLinkRelease (displayLink);
  542. }
  543. static CVReturn displayLinkCallback (CVDisplayLinkRef, const CVTimeStamp*, const CVTimeStamp*,
  544. CVOptionFlags, CVOptionFlags*, void* displayLinkContext)
  545. {
  546. auto* self = (CachedImage*) displayLinkContext;
  547. self->renderFrame();
  548. return kCVReturnSuccess;
  549. }
  550. CVDisplayLinkRef displayLink;
  551. };
  552. std::unique_ptr<CVDisplayLinkWrapper> cvDisplayLinkWrapper;
  553. #endif
  554. std::unique_ptr<ThreadPool> renderThread;
  555. ReferenceCountedArray<OpenGLContext::AsyncWorker, CriticalSection> workQueue;
  556. MessageManager::Lock messageManagerLock;
  557. #if JUCE_IOS
  558. iOSBackgroundProcessCheck backgroundProcessCheck;
  559. #endif
  560. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedImage)
  561. };
  562. //==============================================================================
  563. class OpenGLContext::Attachment : public ComponentMovementWatcher,
  564. private Timer
  565. {
  566. public:
  567. Attachment (OpenGLContext& c, Component& comp)
  568. : ComponentMovementWatcher (&comp), context (c)
  569. {
  570. if (canBeAttached (comp))
  571. attach();
  572. }
  573. ~Attachment() override
  574. {
  575. detach();
  576. }
  577. void detach()
  578. {
  579. auto& comp = *getComponent();
  580. stop();
  581. comp.setCachedComponentImage (nullptr);
  582. context.nativeContext = nullptr;
  583. }
  584. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) override
  585. {
  586. auto& comp = *getComponent();
  587. if (isAttached (comp) != canBeAttached (comp))
  588. componentVisibilityChanged();
  589. if (comp.getWidth() > 0 && comp.getHeight() > 0
  590. && context.nativeContext != nullptr)
  591. {
  592. if (auto* c = CachedImage::get (comp))
  593. c->handleResize();
  594. if (auto* peer = comp.getTopLevelComponent()->getPeer())
  595. context.nativeContext->updateWindowPosition (peer->getAreaCoveredBy (comp));
  596. }
  597. }
  598. using ComponentMovementWatcher::componentMovedOrResized;
  599. void componentPeerChanged() override
  600. {
  601. detach();
  602. componentVisibilityChanged();
  603. }
  604. void componentVisibilityChanged() override
  605. {
  606. auto& comp = *getComponent();
  607. if (canBeAttached (comp))
  608. {
  609. if (isAttached (comp))
  610. comp.repaint(); // (needed when windows are un-minimised)
  611. else
  612. attach();
  613. }
  614. else
  615. {
  616. detach();
  617. }
  618. }
  619. using ComponentMovementWatcher::componentVisibilityChanged;
  620. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  621. void componentBeingDeleted (Component& c) override
  622. {
  623. /* You must call detach() or delete your OpenGLContext to remove it
  624. from a component BEFORE deleting the component that it is using!
  625. */
  626. jassertfalse;
  627. ComponentMovementWatcher::componentBeingDeleted (c);
  628. }
  629. #endif
  630. void update()
  631. {
  632. auto& comp = *getComponent();
  633. if (canBeAttached (comp))
  634. start();
  635. else
  636. stop();
  637. }
  638. private:
  639. OpenGLContext& context;
  640. bool canBeAttached (const Component& comp) noexcept
  641. {
  642. return (! context.overrideCanAttach) && comp.getWidth() > 0 && comp.getHeight() > 0 && isShowingOrMinimised (comp);
  643. }
  644. static bool isShowingOrMinimised (const Component& c)
  645. {
  646. if (! c.isVisible())
  647. return false;
  648. if (auto* p = c.getParentComponent())
  649. return isShowingOrMinimised (*p);
  650. return c.getPeer() != nullptr;
  651. }
  652. static bool isAttached (const Component& comp) noexcept
  653. {
  654. return comp.getCachedComponentImage() != nullptr;
  655. }
  656. void attach()
  657. {
  658. auto& comp = *getComponent();
  659. auto* newCachedImage = new CachedImage (context, comp,
  660. context.openGLPixelFormat,
  661. context.contextToShareWith);
  662. comp.setCachedComponentImage (newCachedImage);
  663. start();
  664. }
  665. void stop()
  666. {
  667. stopTimer();
  668. auto& comp = *getComponent();
  669. #if JUCE_MAC
  670. [[(NSView*) comp.getWindowHandle() window] disableScreenUpdatesUntilFlush];
  671. #endif
  672. if (auto* oldCachedImage = CachedImage::get (comp))
  673. oldCachedImage->stop(); // (must stop this before detaching it from the component)
  674. }
  675. void start()
  676. {
  677. auto& comp = *getComponent();
  678. if (auto* cachedImage = CachedImage::get (comp))
  679. {
  680. cachedImage->start(); // (must wait until this is attached before starting its thread)
  681. cachedImage->updateViewportSize (true);
  682. startTimer (400);
  683. }
  684. }
  685. void timerCallback() override
  686. {
  687. if (auto* cachedImage = CachedImage::get (*getComponent()))
  688. cachedImage->checkViewportBounds();
  689. }
  690. };
  691. //==============================================================================
  692. OpenGLContext::OpenGLContext()
  693. {
  694. }
  695. OpenGLContext::~OpenGLContext()
  696. {
  697. detach();
  698. }
  699. void OpenGLContext::setRenderer (OpenGLRenderer* rendererToUse) noexcept
  700. {
  701. // This method must not be called when the context has already been attached!
  702. // Call it before attaching your context, or use detach() first, before calling this!
  703. jassert (nativeContext == nullptr);
  704. renderer = rendererToUse;
  705. }
  706. void OpenGLContext::setComponentPaintingEnabled (bool shouldPaintComponent) noexcept
  707. {
  708. // This method must not be called when the context has already been attached!
  709. // Call it before attaching your context, or use detach() first, before calling this!
  710. jassert (nativeContext == nullptr);
  711. renderComponents = shouldPaintComponent;
  712. }
  713. void OpenGLContext::setContinuousRepainting (bool shouldContinuouslyRepaint) noexcept
  714. {
  715. continuousRepaint = shouldContinuouslyRepaint;
  716. #if JUCE_MAC
  717. if (auto* component = getTargetComponent())
  718. {
  719. detach();
  720. attachment.reset (new Attachment (*this, *component));
  721. }
  722. #endif
  723. triggerRepaint();
  724. }
  725. void OpenGLContext::setPixelFormat (const OpenGLPixelFormat& preferredPixelFormat) noexcept
  726. {
  727. // This method must not be called when the context has already been attached!
  728. // Call it before attaching your context, or use detach() first, before calling this!
  729. jassert (nativeContext == nullptr);
  730. openGLPixelFormat = preferredPixelFormat;
  731. }
  732. void OpenGLContext::setTextureMagnificationFilter (OpenGLContext::TextureMagnificationFilter magFilterMode) noexcept
  733. {
  734. texMagFilter = magFilterMode;
  735. }
  736. void OpenGLContext::setNativeSharedContext (void* nativeContextToShareWith) noexcept
  737. {
  738. // This method must not be called when the context has already been attached!
  739. // Call it before attaching your context, or use detach() first, before calling this!
  740. jassert (nativeContext == nullptr);
  741. contextToShareWith = nativeContextToShareWith;
  742. }
  743. void OpenGLContext::setMultisamplingEnabled (bool b) noexcept
  744. {
  745. // This method must not be called when the context has already been attached!
  746. // Call it before attaching your context, or use detach() first, before calling this!
  747. jassert (nativeContext == nullptr);
  748. useMultisampling = b;
  749. }
  750. void OpenGLContext::setOpenGLVersionRequired (OpenGLVersion v) noexcept
  751. {
  752. versionRequired = v;
  753. }
  754. void OpenGLContext::attachTo (Component& component)
  755. {
  756. component.repaint();
  757. if (getTargetComponent() != &component)
  758. {
  759. detach();
  760. attachment.reset (new Attachment (*this, component));
  761. }
  762. }
  763. void OpenGLContext::detach()
  764. {
  765. if (auto* a = attachment.get())
  766. {
  767. a->detach(); // must detach before nulling our pointer
  768. attachment.reset();
  769. }
  770. nativeContext = nullptr;
  771. }
  772. bool OpenGLContext::isAttached() const noexcept
  773. {
  774. return nativeContext != nullptr;
  775. }
  776. Component* OpenGLContext::getTargetComponent() const noexcept
  777. {
  778. return attachment != nullptr ? attachment->getComponent() : nullptr;
  779. }
  780. OpenGLContext* OpenGLContext::getContextAttachedTo (Component& c) noexcept
  781. {
  782. if (auto* ci = CachedImage::get (c))
  783. return &(ci->context);
  784. return nullptr;
  785. }
  786. static ThreadLocalValue<OpenGLContext*> currentThreadActiveContext;
  787. OpenGLContext* OpenGLContext::getCurrentContext()
  788. {
  789. return currentThreadActiveContext.get();
  790. }
  791. bool OpenGLContext::makeActive() const noexcept
  792. {
  793. auto& current = currentThreadActiveContext.get();
  794. if (nativeContext != nullptr && nativeContext->makeActive())
  795. {
  796. current = const_cast<OpenGLContext*> (this);
  797. return true;
  798. }
  799. current = nullptr;
  800. return false;
  801. }
  802. bool OpenGLContext::isActive() const noexcept
  803. {
  804. return nativeContext != nullptr && nativeContext->isActive();
  805. }
  806. void OpenGLContext::deactivateCurrentContext()
  807. {
  808. NativeContext::deactivateCurrentContext();
  809. currentThreadActiveContext.get() = nullptr;
  810. }
  811. void OpenGLContext::triggerRepaint()
  812. {
  813. if (auto* cachedImage = getCachedImage())
  814. cachedImage->triggerRepaint();
  815. }
  816. void OpenGLContext::swapBuffers()
  817. {
  818. if (nativeContext != nullptr)
  819. nativeContext->swapBuffers();
  820. }
  821. unsigned int OpenGLContext::getFrameBufferID() const noexcept
  822. {
  823. return nativeContext != nullptr ? nativeContext->getFrameBufferID() : 0;
  824. }
  825. bool OpenGLContext::setSwapInterval (int numFramesPerSwap)
  826. {
  827. return nativeContext != nullptr && nativeContext->setSwapInterval (numFramesPerSwap);
  828. }
  829. int OpenGLContext::getSwapInterval() const
  830. {
  831. return nativeContext != nullptr ? nativeContext->getSwapInterval() : 0;
  832. }
  833. void* OpenGLContext::getRawContext() const noexcept
  834. {
  835. return nativeContext != nullptr ? nativeContext->getRawContext() : nullptr;
  836. }
  837. OpenGLContext::CachedImage* OpenGLContext::getCachedImage() const noexcept
  838. {
  839. if (auto* comp = getTargetComponent())
  840. return CachedImage::get (*comp);
  841. return nullptr;
  842. }
  843. bool OpenGLContext::areShadersAvailable() const
  844. {
  845. auto* c = getCachedImage();
  846. return c != nullptr && c->shadersAvailable;
  847. }
  848. ReferenceCountedObject* OpenGLContext::getAssociatedObject (const char* name) const
  849. {
  850. jassert (name != nullptr);
  851. auto* c = getCachedImage();
  852. // This method must only be called from an openGL rendering callback.
  853. jassert (c != nullptr && nativeContext != nullptr);
  854. jassert (getCurrentContext() != nullptr);
  855. auto index = c->associatedObjectNames.indexOf (name);
  856. return index >= 0 ? c->associatedObjects.getUnchecked (index).get() : nullptr;
  857. }
  858. void OpenGLContext::setAssociatedObject (const char* name, ReferenceCountedObject* newObject)
  859. {
  860. jassert (name != nullptr);
  861. if (auto* c = getCachedImage())
  862. {
  863. // This method must only be called from an openGL rendering callback.
  864. jassert (nativeContext != nullptr);
  865. jassert (getCurrentContext() != nullptr);
  866. const int index = c->associatedObjectNames.indexOf (name);
  867. if (index >= 0)
  868. {
  869. if (newObject != nullptr)
  870. {
  871. c->associatedObjects.set (index, newObject);
  872. }
  873. else
  874. {
  875. c->associatedObjectNames.remove (index);
  876. c->associatedObjects.remove (index);
  877. }
  878. }
  879. else if (newObject != nullptr)
  880. {
  881. c->associatedObjectNames.add (name);
  882. c->associatedObjects.add (newObject);
  883. }
  884. }
  885. }
  886. void OpenGLContext::setImageCacheSize (size_t newSize) noexcept { imageCacheMaxSize = newSize; }
  887. size_t OpenGLContext::getImageCacheSize() const noexcept { return imageCacheMaxSize; }
  888. void OpenGLContext::execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock)
  889. {
  890. if (auto* c = getCachedImage())
  891. c->execute (std::move (workerToUse), shouldBlock);
  892. else
  893. jassertfalse; // You must have attached the context to a component
  894. }
  895. //==============================================================================
  896. struct DepthTestDisabler
  897. {
  898. DepthTestDisabler() noexcept
  899. {
  900. glGetBooleanv (GL_DEPTH_TEST, &wasEnabled);
  901. if (wasEnabled)
  902. glDisable (GL_DEPTH_TEST);
  903. }
  904. ~DepthTestDisabler() noexcept
  905. {
  906. if (wasEnabled)
  907. glEnable (GL_DEPTH_TEST);
  908. }
  909. GLboolean wasEnabled;
  910. };
  911. //==============================================================================
  912. void OpenGLContext::copyTexture (const Rectangle<int>& targetClipArea,
  913. const Rectangle<int>& anchorPosAndTextureSize,
  914. const int contextWidth, const int contextHeight,
  915. bool flippedVertically)
  916. {
  917. if (contextWidth <= 0 || contextHeight <= 0)
  918. return;
  919. JUCE_CHECK_OPENGL_ERROR
  920. glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  921. glEnable (GL_BLEND);
  922. DepthTestDisabler depthDisabler;
  923. if (areShadersAvailable())
  924. {
  925. struct OverlayShaderProgram : public ReferenceCountedObject
  926. {
  927. OverlayShaderProgram (OpenGLContext& context)
  928. : program (context), builder (program), params (program)
  929. {}
  930. static const OverlayShaderProgram& select (OpenGLContext& context)
  931. {
  932. static const char programValueID[] = "juceGLComponentOverlayShader";
  933. OverlayShaderProgram* program = static_cast<OverlayShaderProgram*> (context.getAssociatedObject (programValueID));
  934. if (program == nullptr)
  935. {
  936. program = new OverlayShaderProgram (context);
  937. context.setAssociatedObject (programValueID, program);
  938. }
  939. program->program.use();
  940. return *program;
  941. }
  942. struct ProgramBuilder
  943. {
  944. ProgramBuilder (OpenGLShaderProgram& prog)
  945. {
  946. prog.addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (
  947. "attribute " JUCE_HIGHP " vec2 position;"
  948. "uniform " JUCE_HIGHP " vec2 screenSize;"
  949. "uniform " JUCE_HIGHP " float textureBounds[4];"
  950. "uniform " JUCE_HIGHP " vec2 vOffsetAndScale;"
  951. "varying " JUCE_HIGHP " vec2 texturePos;"
  952. "void main()"
  953. "{"
  954. JUCE_HIGHP " vec2 scaled = position / (0.5 * screenSize.xy);"
  955. "gl_Position = vec4 (scaled.x - 1.0, 1.0 - scaled.y, 0, 1.0);"
  956. "texturePos = (position - vec2 (textureBounds[0], textureBounds[1])) / vec2 (textureBounds[2], textureBounds[3]);"
  957. "texturePos = vec2 (texturePos.x, vOffsetAndScale.x + vOffsetAndScale.y * texturePos.y);"
  958. "}"));
  959. prog.addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (
  960. "uniform sampler2D imageTexture;"
  961. "varying " JUCE_HIGHP " vec2 texturePos;"
  962. "void main()"
  963. "{"
  964. "gl_FragColor = texture2D (imageTexture, texturePos);"
  965. "}"));
  966. prog.link();
  967. }
  968. };
  969. struct Params
  970. {
  971. Params (OpenGLShaderProgram& prog)
  972. : positionAttribute (prog, "position"),
  973. screenSize (prog, "screenSize"),
  974. imageTexture (prog, "imageTexture"),
  975. textureBounds (prog, "textureBounds"),
  976. vOffsetAndScale (prog, "vOffsetAndScale")
  977. {}
  978. void set (const float targetWidth, const float targetHeight, const Rectangle<float>& bounds, bool flipVertically) const
  979. {
  980. const GLfloat m[] = { bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight() };
  981. textureBounds.set (m, 4);
  982. imageTexture.set (0);
  983. screenSize.set (targetWidth, targetHeight);
  984. vOffsetAndScale.set (flipVertically ? 0.0f : 1.0f,
  985. flipVertically ? 1.0f : -1.0f);
  986. }
  987. OpenGLShaderProgram::Attribute positionAttribute;
  988. OpenGLShaderProgram::Uniform screenSize, imageTexture, textureBounds, vOffsetAndScale;
  989. };
  990. OpenGLShaderProgram program;
  991. ProgramBuilder builder;
  992. Params params;
  993. };
  994. auto left = (GLshort) targetClipArea.getX();
  995. auto top = (GLshort) targetClipArea.getY();
  996. auto right = (GLshort) targetClipArea.getRight();
  997. auto bottom = (GLshort) targetClipArea.getBottom();
  998. const GLshort vertices[] = { left, bottom, right, bottom, left, top, right, top };
  999. auto& program = OverlayShaderProgram::select (*this);
  1000. program.params.set ((float) contextWidth, (float) contextHeight, anchorPosAndTextureSize.toFloat(), flippedVertically);
  1001. GLuint vertexBuffer = 0;
  1002. extensions.glGenBuffers (1, &vertexBuffer);
  1003. extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
  1004. extensions.glBufferData (GL_ARRAY_BUFFER, sizeof (vertices), vertices, GL_STATIC_DRAW);
  1005. auto index = (GLuint) program.params.positionAttribute.attributeID;
  1006. extensions.glVertexAttribPointer (index, 2, GL_SHORT, GL_FALSE, 4, nullptr);
  1007. extensions.glEnableVertexAttribArray (index);
  1008. JUCE_CHECK_OPENGL_ERROR
  1009. if (extensions.glCheckFramebufferStatus (GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
  1010. {
  1011. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  1012. extensions.glBindBuffer (GL_ARRAY_BUFFER, 0);
  1013. extensions.glUseProgram (0);
  1014. extensions.glDisableVertexAttribArray (index);
  1015. extensions.glDeleteBuffers (1, &vertexBuffer);
  1016. }
  1017. else
  1018. {
  1019. clearGLError();
  1020. }
  1021. }
  1022. else
  1023. {
  1024. jassert (attachment == nullptr); // Running on an old graphics card!
  1025. }
  1026. JUCE_CHECK_OPENGL_ERROR
  1027. }
  1028. #if JUCE_ANDROID
  1029. EGLDisplay OpenGLContext::NativeContext::display = EGL_NO_DISPLAY;
  1030. EGLDisplay OpenGLContext::NativeContext::config;
  1031. void OpenGLContext::NativeContext::surfaceCreated (LocalRef<jobject> holder)
  1032. {
  1033. ignoreUnused (holder);
  1034. if (auto* cachedImage = CachedImage::get (component))
  1035. {
  1036. if (auto* pool = cachedImage->renderThread.get())
  1037. {
  1038. if (! pool->contains (cachedImage))
  1039. {
  1040. cachedImage->resume();
  1041. cachedImage->context.triggerRepaint();
  1042. }
  1043. }
  1044. }
  1045. }
  1046. void OpenGLContext::NativeContext::surfaceDestroyed (LocalRef<jobject> holder)
  1047. {
  1048. ignoreUnused (holder);
  1049. // unlike the name suggests this will be called just before the
  1050. // surface is destroyed. We need to pause the render thread.
  1051. if (auto* cachedImage = CachedImage::get (component))
  1052. {
  1053. cachedImage->pause();
  1054. if (auto* threadPool = cachedImage->renderThread.get())
  1055. threadPool->waitForJobToFinish (cachedImage, -1);
  1056. }
  1057. }
  1058. #endif
  1059. } // namespace juce