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.

1256 lines
38KB

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