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.

1238 lines
37KB

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