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.

1255 lines
38KB

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