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.

1295 lines
39KB

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