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.

1053 lines
33KB

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