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.

1086 lines
34KB

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