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.

1662 lines
52KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #if JUCE_MAC
  19. #include <juce_gui_basics/native/juce_mac_PerScreenDisplayLinks.h>
  20. #endif
  21. namespace juce
  22. {
  23. #if JUCE_IOS
  24. struct AppInactivityCallback // NB: this is a duplicate of an internal declaration in juce_core
  25. {
  26. virtual ~AppInactivityCallback() {}
  27. virtual void appBecomingInactive() = 0;
  28. };
  29. extern Array<AppInactivityCallback*> appBecomingInactiveCallbacks;
  30. // On iOS, all GL calls will crash when the app is running in the background, so
  31. // this prevents them from happening (which some messy locking behaviour)
  32. struct iOSBackgroundProcessCheck : public AppInactivityCallback
  33. {
  34. iOSBackgroundProcessCheck() { isBackgroundProcess(); appBecomingInactiveCallbacks.add (this); }
  35. ~iOSBackgroundProcessCheck() override { appBecomingInactiveCallbacks.removeAllInstancesOf (this); }
  36. bool isBackgroundProcess()
  37. {
  38. const bool b = Process::isForegroundProcess();
  39. isForeground.set (b ? 1 : 0);
  40. return ! b;
  41. }
  42. void appBecomingInactive() override
  43. {
  44. int counter = 2000;
  45. while (--counter > 0 && isForeground.get() != 0)
  46. Thread::sleep (1);
  47. }
  48. private:
  49. Atomic<int> isForeground;
  50. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (iOSBackgroundProcessCheck)
  51. };
  52. #endif
  53. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  54. extern JUCE_API double getScaleFactorForWindow (HWND);
  55. #endif
  56. static bool contextHasTextureNpotFeature()
  57. {
  58. if (getOpenGLVersion() >= Version (2))
  59. return true;
  60. // If the version is < 2, we can't use the newer extension-checking API
  61. // so we have to use glGetString
  62. const auto* extensionsBegin = glGetString (GL_EXTENSIONS);
  63. if (extensionsBegin == nullptr)
  64. return false;
  65. const auto* extensionsEnd = findNullTerminator (extensionsBegin);
  66. const std::string extensionsString (extensionsBegin, extensionsEnd);
  67. const auto stringTokens = StringArray::fromTokens (extensionsString.c_str(), false);
  68. return stringTokens.contains ("GL_ARB_texture_non_power_of_two");
  69. }
  70. //==============================================================================
  71. class OpenGLContext::CachedImage : public CachedComponentImage
  72. {
  73. template <typename T, typename U>
  74. static constexpr bool isFlagSet (const T& t, const U& u) { return (t & u) != 0; }
  75. struct AreaAndScale
  76. {
  77. Rectangle<int> area;
  78. double scale;
  79. auto tie() const { return std::tie (area, scale); }
  80. auto operator== (const AreaAndScale& other) const { return tie() == other.tie(); }
  81. auto operator!= (const AreaAndScale& other) const { return tie() != other.tie(); }
  82. };
  83. class LockedAreaAndScale
  84. {
  85. public:
  86. auto get() const
  87. {
  88. const ScopedLock lock (mutex);
  89. return data;
  90. }
  91. template <typename Fn>
  92. void set (const AreaAndScale& d, Fn&& ifDifferent)
  93. {
  94. const auto old = [&]
  95. {
  96. const ScopedLock lock (mutex);
  97. return std::exchange (data, d);
  98. }();
  99. if (old != d)
  100. ifDifferent();
  101. }
  102. private:
  103. CriticalSection mutex;
  104. AreaAndScale data { {}, 1.0 };
  105. };
  106. public:
  107. CachedImage (OpenGLContext& c, Component& comp,
  108. const OpenGLPixelFormat& pixFormat, void* contextToShare)
  109. : context (c),
  110. component (comp)
  111. {
  112. nativeContext.reset (new NativeContext (component, pixFormat, contextToShare,
  113. c.useMultisampling, c.versionRequired));
  114. if (nativeContext->createdOk())
  115. context.nativeContext = nativeContext.get();
  116. else
  117. nativeContext.reset();
  118. }
  119. ~CachedImage() override
  120. {
  121. stop();
  122. }
  123. //==============================================================================
  124. void start()
  125. {
  126. if (nativeContext != nullptr)
  127. resume();
  128. }
  129. void stop()
  130. {
  131. // make sure everything has finished executing
  132. state |= StateFlags::pendingDestruction;
  133. if (workQueue.size() > 0)
  134. {
  135. if (! renderThread->contains (this))
  136. resume();
  137. while (workQueue.size() != 0)
  138. Thread::sleep (20);
  139. }
  140. pause();
  141. }
  142. //==============================================================================
  143. void pause()
  144. {
  145. renderThread->remove (this);
  146. if ((state.fetch_and (~StateFlags::initialised) & StateFlags::initialised) != 0)
  147. {
  148. context.makeActive();
  149. shutdownOnThread();
  150. OpenGLContext::deactivateCurrentContext();
  151. }
  152. }
  153. void resume()
  154. {
  155. renderThread->add (this);
  156. }
  157. //==============================================================================
  158. void paint (Graphics&) override
  159. {
  160. if (MessageManager::getInstance()->isThisTheMessageThread())
  161. {
  162. updateViewportSize();
  163. }
  164. else
  165. {
  166. // If you hit this assertion, it's because paint has been called from a thread other
  167. // than the message thread. This commonly happens when nesting OpenGL contexts, because
  168. // the 'outer' OpenGL renderer will attempt to call paint on the 'inner' context's
  169. // component from the OpenGL thread.
  170. // Nesting OpenGL contexts is not directly supported, however there is a workaround:
  171. // https://forum.juce.com/t/opengl-how-do-3d-with-custom-shaders-and-2d-with-juce-paint-methods-work-together/28026/7
  172. jassertfalse;
  173. }
  174. }
  175. bool invalidateAll() override
  176. {
  177. validArea.clear();
  178. triggerRepaint();
  179. return false;
  180. }
  181. bool invalidate (const Rectangle<int>& area) override
  182. {
  183. validArea.subtract (area.toFloat().transformedBy (transform).getSmallestIntegerContainer());
  184. triggerRepaint();
  185. return false;
  186. }
  187. void releaseResources() override
  188. {
  189. stop();
  190. }
  191. void triggerRepaint()
  192. {
  193. state |= (StateFlags::pendingRender | StateFlags::paintComponents);
  194. renderThread->triggerRepaint();
  195. }
  196. //==============================================================================
  197. bool ensureFrameBufferSize (Rectangle<int> viewportArea)
  198. {
  199. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  200. auto fbW = cachedImageFrameBuffer.getWidth();
  201. auto fbH = cachedImageFrameBuffer.getHeight();
  202. if (fbW != viewportArea.getWidth() || fbH != viewportArea.getHeight() || ! cachedImageFrameBuffer.isValid())
  203. {
  204. if (! cachedImageFrameBuffer.initialise (context, viewportArea.getWidth(), viewportArea.getHeight()))
  205. return false;
  206. validArea.clear();
  207. JUCE_CHECK_OPENGL_ERROR
  208. }
  209. return true;
  210. }
  211. void clearRegionInFrameBuffer (const RectangleList<int>& list)
  212. {
  213. glClearColor (0, 0, 0, 0);
  214. glEnable (GL_SCISSOR_TEST);
  215. auto previousFrameBufferTarget = OpenGLFrameBuffer::getCurrentFrameBufferTarget();
  216. cachedImageFrameBuffer.makeCurrentRenderingTarget();
  217. auto imageH = cachedImageFrameBuffer.getHeight();
  218. for (auto& r : list)
  219. {
  220. glScissor (r.getX(), imageH - r.getBottom(), r.getWidth(), r.getHeight());
  221. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  222. }
  223. glDisable (GL_SCISSOR_TEST);
  224. context.extensions.glBindFramebuffer (GL_FRAMEBUFFER, previousFrameBufferTarget);
  225. JUCE_CHECK_OPENGL_ERROR
  226. }
  227. struct ScopedContextActivator
  228. {
  229. bool activate (OpenGLContext& ctx)
  230. {
  231. if (! active)
  232. active = ctx.makeActive();
  233. return active;
  234. }
  235. ~ScopedContextActivator()
  236. {
  237. if (active)
  238. OpenGLContext::deactivateCurrentContext();
  239. }
  240. private:
  241. bool active = false;
  242. };
  243. enum class RenderStatus
  244. {
  245. nominal,
  246. messageThreadAborted,
  247. noWork,
  248. };
  249. RenderStatus renderFrame (MessageManager::Lock& mmLock)
  250. {
  251. if (! isFlagSet (state, StateFlags::initialised))
  252. {
  253. switch (initialiseOnThread())
  254. {
  255. case InitResult::fatal:
  256. case InitResult::retry: return RenderStatus::noWork;
  257. case InitResult::success: break;
  258. }
  259. }
  260. state |= StateFlags::initialised;
  261. #if JUCE_IOS
  262. if (backgroundProcessCheck.isBackgroundProcess())
  263. return RenderStatus::noWork;
  264. #endif
  265. std::optional<MessageManager::Lock::ScopedTryLockType> scopedLock;
  266. ScopedContextActivator contextActivator;
  267. const auto stateToUse = state.fetch_and (StateFlags::persistent);
  268. if (! isFlagSet (stateToUse, StateFlags::pendingRender) && ! context.continuousRepaint)
  269. return RenderStatus::noWork;
  270. const auto isUpdating = isFlagSet (stateToUse, StateFlags::paintComponents);
  271. if (context.renderComponents && isUpdating)
  272. {
  273. bool abortScope = false;
  274. // If we early-exit here, we need to restore these flags so that the render is
  275. // attempted again in the next time slice.
  276. const ScopeGuard scope { [&] { if (! abortScope) state |= stateToUse; } };
  277. // This avoids hogging the message thread when doing intensive rendering.
  278. std::this_thread::sleep_until (lastMMLockReleaseTime + std::chrono::milliseconds { 2 });
  279. if (renderThread->isListChanging())
  280. return RenderStatus::messageThreadAborted;
  281. doWorkWhileWaitingForLock (contextActivator);
  282. scopedLock.emplace (mmLock);
  283. // If we can't get the lock here, it's probably because a context has been removed
  284. // on the main thread.
  285. // We return, just in case this renderer needs to be removed from the rendering thread.
  286. // If another renderer is being removed instead, then we should be able to get the lock
  287. // next time round.
  288. if (! scopedLock->isLocked())
  289. return RenderStatus::messageThreadAborted;
  290. abortScope = true;
  291. }
  292. if (! contextActivator.activate (context))
  293. return RenderStatus::noWork;
  294. {
  295. NativeContext::Locker locker (*nativeContext);
  296. JUCE_CHECK_OPENGL_ERROR
  297. doWorkWhileWaitingForLock (contextActivator);
  298. const auto currentAreaAndScale = areaAndScale.get();
  299. const auto viewportArea = currentAreaAndScale.area;
  300. if (context.renderer != nullptr)
  301. {
  302. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  303. context.currentRenderScale = currentAreaAndScale.scale;
  304. context.renderer->renderOpenGL();
  305. clearGLError();
  306. bindVertexArray();
  307. }
  308. if (context.renderComponents)
  309. {
  310. if (isUpdating)
  311. {
  312. paintComponent (currentAreaAndScale);
  313. if (! isFlagSet (state, StateFlags::initialised))
  314. return RenderStatus::noWork;
  315. scopedLock.reset();
  316. lastMMLockReleaseTime = std::chrono::steady_clock::now();
  317. }
  318. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  319. drawComponentBuffer();
  320. }
  321. }
  322. nativeContext->swapBuffers();
  323. return RenderStatus::nominal;
  324. }
  325. void updateViewportSize()
  326. {
  327. JUCE_ASSERT_MESSAGE_THREAD
  328. if (auto* peer = component.getPeer())
  329. {
  330. #if JUCE_MAC
  331. updateScreen();
  332. const auto displayScale = Desktop::getInstance().getGlobalScaleFactor() * [this]
  333. {
  334. if (auto* view = getCurrentView())
  335. {
  336. if ([view respondsToSelector: @selector (backingScaleFactor)])
  337. return [(id) view backingScaleFactor];
  338. if (auto* window = [view window])
  339. return [window backingScaleFactor];
  340. }
  341. return areaAndScale.get().scale;
  342. }();
  343. #else
  344. const auto displayScale = Desktop::getInstance().getDisplays()
  345. .getDisplayForRect (component.getTopLevelComponent()
  346. ->getScreenBounds())
  347. ->scale;
  348. #endif
  349. const auto localBounds = component.getLocalBounds();
  350. const auto newArea = peer->getComponent().getLocalArea (&component, localBounds).withZeroOrigin() * displayScale;
  351. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  352. // Some hosts (Pro Tools 2022.7) do not take the current DPI into account when sizing
  353. // plugin editor windows. Instead of querying the OS for the DPI of the editor window,
  354. // we approximate based on the physical size of the window that was actually provided
  355. // for the context to draw into. This may break if the OpenGL context's component is
  356. // scaled differently in its width and height - but in this case, a single scale factor
  357. // isn't that helpful anyway.
  358. const auto newScale = (float) newArea.getWidth() / (float) localBounds.getWidth();
  359. #else
  360. const auto newScale = (float) displayScale;
  361. #endif
  362. areaAndScale.set ({ newArea, newScale }, [&]
  363. {
  364. // Transform is only accessed when the message manager is locked
  365. transform = AffineTransform::scale ((float) newArea.getWidth() / (float) localBounds.getWidth(),
  366. (float) newArea.getHeight() / (float) localBounds.getHeight());
  367. nativeContext->updateWindowPosition (peer->getAreaCoveredBy (component));
  368. invalidateAll();
  369. });
  370. }
  371. }
  372. void bindVertexArray() noexcept
  373. {
  374. if (shouldUseCustomVAO())
  375. if (vertexArrayObject != 0)
  376. context.extensions.glBindVertexArray (vertexArrayObject);
  377. }
  378. void checkViewportBounds()
  379. {
  380. auto screenBounds = component.getTopLevelComponent()->getScreenBounds();
  381. if (lastScreenBounds != screenBounds)
  382. {
  383. updateViewportSize();
  384. lastScreenBounds = screenBounds;
  385. }
  386. }
  387. void paintComponent (const AreaAndScale& currentAreaAndScale)
  388. {
  389. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  390. // you mustn't set your own cached image object when attaching a GL context!
  391. jassert (get (component) == this);
  392. if (! ensureFrameBufferSize (currentAreaAndScale.area))
  393. return;
  394. RectangleList<int> invalid (currentAreaAndScale.area);
  395. invalid.subtract (validArea);
  396. validArea = currentAreaAndScale.area;
  397. if (! invalid.isEmpty())
  398. {
  399. clearRegionInFrameBuffer (invalid);
  400. {
  401. std::unique_ptr<LowLevelGraphicsContext> g (createOpenGLGraphicsContext (context, cachedImageFrameBuffer));
  402. g->clipToRectangleList (invalid);
  403. g->addTransform (transform);
  404. paintOwner (*g);
  405. JUCE_CHECK_OPENGL_ERROR
  406. }
  407. if (! context.isActive())
  408. context.makeActive();
  409. }
  410. JUCE_CHECK_OPENGL_ERROR
  411. }
  412. void drawComponentBuffer()
  413. {
  414. if (contextRequiresTexture2DEnableDisable())
  415. glEnable (GL_TEXTURE_2D);
  416. #if JUCE_WINDOWS
  417. // some stupidly old drivers are missing this function, so try to at least avoid a crash here,
  418. // but if you hit this assertion you may want to have your own version check before using the
  419. // component rendering stuff on such old drivers.
  420. jassert (context.extensions.glActiveTexture != nullptr);
  421. if (context.extensions.glActiveTexture != nullptr)
  422. #endif
  423. {
  424. context.extensions.glActiveTexture (GL_TEXTURE0);
  425. }
  426. glBindTexture (GL_TEXTURE_2D, cachedImageFrameBuffer.getTextureID());
  427. bindVertexArray();
  428. const Rectangle<int> cacheBounds (cachedImageFrameBuffer.getWidth(), cachedImageFrameBuffer.getHeight());
  429. context.copyTexture (cacheBounds, cacheBounds, cacheBounds.getWidth(), cacheBounds.getHeight(), false);
  430. glBindTexture (GL_TEXTURE_2D, 0);
  431. JUCE_CHECK_OPENGL_ERROR
  432. }
  433. void paintOwner (LowLevelGraphicsContext& llgc)
  434. {
  435. Graphics g (llgc);
  436. #if JUCE_ENABLE_REPAINT_DEBUGGING
  437. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  438. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  439. #endif
  440. {
  441. g.saveState();
  442. }
  443. #endif
  444. JUCE_TRY
  445. {
  446. component.paintEntireComponent (g, false);
  447. }
  448. JUCE_CATCH_EXCEPTION
  449. #if JUCE_ENABLE_REPAINT_DEBUGGING
  450. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  451. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  452. #endif
  453. {
  454. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  455. // clearly when things are being repainted.
  456. g.restoreState();
  457. static Random rng;
  458. g.fillAll (Colour ((uint8) rng.nextInt (255),
  459. (uint8) rng.nextInt (255),
  460. (uint8) rng.nextInt (255),
  461. (uint8) 0x50));
  462. }
  463. #endif
  464. }
  465. void handleResize()
  466. {
  467. updateViewportSize();
  468. #if JUCE_MAC
  469. if (isFlagSet (state, StateFlags::initialised))
  470. {
  471. [nativeContext->view update];
  472. // We're already on the message thread, no need to lock it again.
  473. MessageManager::Lock mml;
  474. renderFrame (mml);
  475. }
  476. #endif
  477. }
  478. //==============================================================================
  479. InitResult initialiseOnThread()
  480. {
  481. // On android, this can get called twice, so drop any previous state.
  482. associatedObjectNames.clear();
  483. associatedObjects.clear();
  484. cachedImageFrameBuffer.release();
  485. context.makeActive();
  486. if (const auto nativeResult = nativeContext->initialiseOnRenderThread (context); nativeResult != InitResult::success)
  487. return nativeResult;
  488. #if JUCE_ANDROID
  489. // On android the context may be created in initialiseOnRenderThread
  490. // and we therefore need to call makeActive again
  491. context.makeActive();
  492. #endif
  493. gl::loadFunctions();
  494. if (shouldUseCustomVAO())
  495. {
  496. context.extensions.glGenVertexArrays (1, &vertexArrayObject);
  497. bindVertexArray();
  498. }
  499. #if JUCE_DEBUG
  500. if (getOpenGLVersion() >= Version { 4, 3 } && glDebugMessageCallback != nullptr)
  501. {
  502. glEnable (GL_DEBUG_OUTPUT);
  503. glDebugMessageCallback ([] (GLenum type, GLenum, GLuint, GLenum severity, GLsizei, const GLchar* message, const void*)
  504. {
  505. // This may reiterate issues that are also flagged by JUCE_CHECK_OPENGL_ERROR.
  506. // The advantage of this callback is that it will catch *all* errors, even if we
  507. // forget to check manually.
  508. DBG ("OpenGL DBG message: " << message);
  509. jassertquiet (type != GL_DEBUG_TYPE_ERROR && severity != GL_DEBUG_SEVERITY_HIGH);
  510. }, nullptr);
  511. }
  512. #endif
  513. const auto currentViewportArea = areaAndScale.get().area;
  514. glViewport (0, 0, currentViewportArea.getWidth(), currentViewportArea.getHeight());
  515. nativeContext->setSwapInterval (1);
  516. #if ! JUCE_OPENGL_ES
  517. JUCE_CHECK_OPENGL_ERROR
  518. shadersAvailable = OpenGLShaderProgram::getLanguageVersion() > 0;
  519. clearGLError();
  520. #endif
  521. textureNpotSupported = contextHasTextureNpotFeature();
  522. if (context.renderer != nullptr)
  523. context.renderer->newOpenGLContextCreated();
  524. return InitResult::success;
  525. }
  526. void shutdownOnThread()
  527. {
  528. if (context.renderer != nullptr)
  529. context.renderer->openGLContextClosing();
  530. if (vertexArrayObject != 0)
  531. context.extensions.glDeleteVertexArrays (1, &vertexArrayObject);
  532. associatedObjectNames.clear();
  533. associatedObjects.clear();
  534. cachedImageFrameBuffer.release();
  535. nativeContext->shutdownOnRenderThread();
  536. }
  537. /* Returns true if the context requires a non-zero vertex array object (VAO) to be bound.
  538. If the context is a compatibility context, we can just pretend that VAOs don't exist,
  539. and use the default VAO all the time instead. This provides a more consistent experience
  540. in user code, which might make calls (like glVertexPointer()) that only work when VAO 0 is
  541. bound in OpenGL 3.2+.
  542. */
  543. bool shouldUseCustomVAO() const
  544. {
  545. #if JUCE_OPENGL_ES
  546. return false;
  547. #else
  548. clearGLError();
  549. GLint mask = 0;
  550. glGetIntegerv (GL_CONTEXT_PROFILE_MASK, &mask);
  551. // The context isn't aware of the profile mask, so it pre-dates the core profile
  552. if (glGetError() == GL_INVALID_ENUM)
  553. return false;
  554. // Also assumes a compatibility profile if the mask is completely empty for some reason
  555. return (mask & (GLint) GL_CONTEXT_CORE_PROFILE_BIT) != 0;
  556. #endif
  557. }
  558. //==============================================================================
  559. struct BlockingWorker : public OpenGLContext::AsyncWorker
  560. {
  561. BlockingWorker (OpenGLContext::AsyncWorker::Ptr && workerToUse)
  562. : originalWorker (std::move (workerToUse))
  563. {}
  564. void operator() (OpenGLContext& calleeContext)
  565. {
  566. if (originalWorker != nullptr)
  567. (*originalWorker) (calleeContext);
  568. finishedSignal.signal();
  569. }
  570. void block() noexcept { finishedSignal.wait(); }
  571. OpenGLContext::AsyncWorker::Ptr originalWorker;
  572. WaitableEvent finishedSignal;
  573. };
  574. void doWorkWhileWaitingForLock (ScopedContextActivator& contextActivator)
  575. {
  576. while (const auto work = workQueue.removeAndReturn (0))
  577. {
  578. if (renderThread->isListChanging() || ! contextActivator.activate (context))
  579. break;
  580. NativeContext::Locker locker (*nativeContext);
  581. (*work) (context);
  582. clearGLError();
  583. }
  584. }
  585. void execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock)
  586. {
  587. if (! isFlagSet (state, StateFlags::pendingDestruction))
  588. {
  589. if (shouldBlock)
  590. {
  591. auto blocker = new BlockingWorker (std::move (workerToUse));
  592. OpenGLContext::AsyncWorker::Ptr worker (*blocker);
  593. workQueue.add (worker);
  594. renderThread->abortLock();
  595. context.triggerRepaint();
  596. blocker->block();
  597. }
  598. else
  599. {
  600. workQueue.add (std::move (workerToUse));
  601. renderThread->abortLock();
  602. context.triggerRepaint();
  603. }
  604. }
  605. else
  606. {
  607. jassertfalse; // you called execute AFTER you detached your OpenGLContext
  608. }
  609. }
  610. //==============================================================================
  611. static CachedImage* get (Component& c) noexcept
  612. {
  613. return dynamic_cast<CachedImage*> (c.getCachedComponentImage());
  614. }
  615. class RenderThread
  616. {
  617. public:
  618. RenderThread() = default;
  619. ~RenderThread()
  620. {
  621. flags.setDestructing();
  622. thread.join();
  623. }
  624. void add (CachedImage* x)
  625. {
  626. const std::scoped_lock lock { listMutex };
  627. images.push_back (x);
  628. }
  629. void remove (CachedImage* x)
  630. {
  631. JUCE_ASSERT_MESSAGE_THREAD;
  632. flags.setSafe (false);
  633. abortLock();
  634. {
  635. const std::scoped_lock lock { callbackMutex, listMutex };
  636. images.remove (x);
  637. }
  638. flags.setSafe (true);
  639. }
  640. bool contains (CachedImage* x)
  641. {
  642. const std::scoped_lock lock { listMutex };
  643. return std::find (images.cbegin(), images.cend(), x) != images.cend();
  644. }
  645. void triggerRepaint() { flags.setRenderRequested(); }
  646. void abortLock() { messageManagerLock.abort(); }
  647. bool isListChanging() { return ! flags.isSafe(); }
  648. private:
  649. RenderStatus renderAll()
  650. {
  651. auto result = RenderStatus::noWork;
  652. const std::scoped_lock lock { callbackMutex, listMutex };
  653. for (auto* x : images)
  654. {
  655. listMutex.unlock();
  656. const ScopeGuard scope { [&] { listMutex.lock(); } };
  657. const auto status = x->renderFrame (messageManagerLock);
  658. switch (status)
  659. {
  660. case RenderStatus::noWork: break;
  661. case RenderStatus::nominal: result = RenderStatus::nominal; break;
  662. case RenderStatus::messageThreadAborted: return RenderStatus::messageThreadAborted;
  663. }
  664. }
  665. return result;
  666. }
  667. /* Allows the main thread to communicate changes to the render thread.
  668. When the render thread needs to change in some way (asked to resume rendering,
  669. a renderer is added/removed, or the thread needs to stop prior to destruction),
  670. the main thread can set the appropriate flag on this structure. The render thread
  671. will call waitForWork() repeatedly, pausing when the render thread has no work to do,
  672. and resuming when requested by the main thread.
  673. */
  674. class Flags
  675. {
  676. public:
  677. void setDestructing() { update ([] (auto& f) { f |= destructorCalled; }); }
  678. void setRenderRequested() { update ([] (auto& f) { f |= renderRequested; }); }
  679. void setSafe (const bool safe)
  680. {
  681. update ([safe] (auto& f)
  682. {
  683. if (safe)
  684. f |= listSafe;
  685. else
  686. f &= ~listSafe;
  687. });
  688. }
  689. bool isSafe()
  690. {
  691. const std::scoped_lock lock { mutex };
  692. return (flags & listSafe) != 0;
  693. }
  694. /* Blocks until the 'safe' flag is set, and at least one other flag is set.
  695. After returning, the renderRequested flag will be unset.
  696. Returns true if rendering should continue.
  697. */
  698. bool waitForWork (bool requestRender)
  699. {
  700. std::unique_lock lock { mutex };
  701. flags |= (requestRender ? renderRequested : 0);
  702. condvar.wait (lock, [this] { return flags > listSafe; });
  703. flags &= ~renderRequested;
  704. return ((flags & destructorCalled) == 0);
  705. }
  706. private:
  707. template <typename Fn>
  708. void update (Fn fn)
  709. {
  710. {
  711. const std::scoped_lock lock { mutex };
  712. fn (flags);
  713. }
  714. condvar.notify_one();
  715. }
  716. enum
  717. {
  718. renderRequested = 1 << 0,
  719. destructorCalled = 1 << 1,
  720. listSafe = 1 << 2
  721. };
  722. std::mutex mutex;
  723. std::condition_variable condvar;
  724. int flags = listSafe;
  725. };
  726. MessageManager::Lock messageManagerLock;
  727. std::mutex listMutex, callbackMutex;
  728. std::list<CachedImage*> images;
  729. Flags flags;
  730. std::thread thread { [this]
  731. {
  732. Thread::setCurrentThreadName ("OpenGL Renderer");
  733. while (flags.waitForWork (renderAll() != RenderStatus::noWork)) {}
  734. } };
  735. };
  736. //==============================================================================
  737. friend class NativeContext;
  738. std::unique_ptr<NativeContext> nativeContext;
  739. OpenGLContext& context;
  740. Component& component;
  741. SharedResourcePointer<RenderThread> renderThread;
  742. OpenGLFrameBuffer cachedImageFrameBuffer;
  743. RectangleList<int> validArea;
  744. Rectangle<int> lastScreenBounds;
  745. AffineTransform transform;
  746. GLuint vertexArrayObject = 0;
  747. LockedAreaAndScale areaAndScale;
  748. StringArray associatedObjectNames;
  749. ReferenceCountedArray<ReferenceCountedObject> associatedObjects;
  750. WaitableEvent canPaintNowFlag, finishedPaintingFlag;
  751. #if JUCE_OPENGL_ES
  752. bool shadersAvailable = true;
  753. #else
  754. bool shadersAvailable = false;
  755. #endif
  756. bool textureNpotSupported = false;
  757. std::chrono::steady_clock::time_point lastMMLockReleaseTime{};
  758. #if JUCE_MAC
  759. NSView* getCurrentView() const
  760. {
  761. JUCE_ASSERT_MESSAGE_THREAD;
  762. if (auto* peer = component.getPeer())
  763. return static_cast<NSView*> (peer->getNativeHandle());
  764. return nullptr;
  765. }
  766. NSWindow* getCurrentWindow() const
  767. {
  768. JUCE_ASSERT_MESSAGE_THREAD;
  769. if (auto* view = getCurrentView())
  770. return [view window];
  771. return nullptr;
  772. }
  773. NSScreen* getCurrentScreen() const
  774. {
  775. JUCE_ASSERT_MESSAGE_THREAD;
  776. if (auto* window = getCurrentWindow())
  777. return [window screen];
  778. return nullptr;
  779. }
  780. void updateScreen()
  781. {
  782. const auto screen = getCurrentScreen();
  783. const auto display = ScopedDisplayLink::getDisplayIdForScreen (screen);
  784. if (lastDisplay.exchange (display) == display)
  785. return;
  786. const auto newRefreshPeriod = sharedDisplayLinks->getNominalVideoRefreshPeriodSForScreen (display);
  787. if (newRefreshPeriod != 0.0 && std::exchange (refreshPeriod, newRefreshPeriod) != newRefreshPeriod)
  788. nativeContext->setNominalVideoRefreshPeriodS (newRefreshPeriod);
  789. updateColourSpace();
  790. }
  791. void updateColourSpace()
  792. {
  793. if (auto* view = nativeContext->getNSView())
  794. if (auto* window = [view window])
  795. [window setColorSpace: [NSColorSpace sRGBColorSpace]];
  796. }
  797. std::atomic<CGDirectDisplayID> lastDisplay { 0 };
  798. double refreshPeriod = 0.0;
  799. FunctionNotificationCenterObserver observer { NSWindowDidChangeScreenNotification,
  800. getCurrentWindow(),
  801. [this] { updateScreen(); } };
  802. // Note: the NSViewComponentPeer also has a SharedResourcePointer<PerScreenDisplayLinks> to
  803. // avoid unnecessarily duplicating display-link threads.
  804. SharedResourcePointer<PerScreenDisplayLinks> sharedDisplayLinks;
  805. #endif
  806. enum StateFlags
  807. {
  808. pendingRender = 1 << 0,
  809. paintComponents = 1 << 1,
  810. pendingDestruction = 1 << 2,
  811. initialised = 1 << 3,
  812. // Flags that may change state after each frame
  813. transient = pendingRender | paintComponents,
  814. // Flags that should retain their state after each frame
  815. persistent = initialised | pendingDestruction
  816. };
  817. std::atomic<int> state { 0 };
  818. ReferenceCountedArray<OpenGLContext::AsyncWorker, CriticalSection> workQueue;
  819. #if JUCE_IOS
  820. iOSBackgroundProcessCheck backgroundProcessCheck;
  821. #endif
  822. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedImage)
  823. };
  824. //==============================================================================
  825. class OpenGLContext::Attachment : public ComponentMovementWatcher,
  826. private Timer
  827. {
  828. public:
  829. Attachment (OpenGLContext& c, Component& comp)
  830. : ComponentMovementWatcher (&comp), context (c)
  831. {
  832. if (canBeAttached (comp))
  833. attach();
  834. }
  835. ~Attachment() override
  836. {
  837. detach();
  838. }
  839. void detach()
  840. {
  841. auto& comp = *getComponent();
  842. stop();
  843. comp.setCachedComponentImage (nullptr);
  844. context.nativeContext = nullptr;
  845. }
  846. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) override
  847. {
  848. auto& comp = *getComponent();
  849. if (isAttached (comp) != canBeAttached (comp))
  850. componentVisibilityChanged();
  851. if (comp.getWidth() > 0 && comp.getHeight() > 0
  852. && context.nativeContext != nullptr)
  853. {
  854. if (auto* c = CachedImage::get (comp))
  855. c->handleResize();
  856. if (auto* peer = comp.getTopLevelComponent()->getPeer())
  857. context.nativeContext->updateWindowPosition (peer->getAreaCoveredBy (comp));
  858. }
  859. }
  860. using ComponentMovementWatcher::componentMovedOrResized;
  861. void componentPeerChanged() override
  862. {
  863. detach();
  864. componentVisibilityChanged();
  865. }
  866. void componentVisibilityChanged() override
  867. {
  868. auto& comp = *getComponent();
  869. if (canBeAttached (comp))
  870. {
  871. if (isAttached (comp))
  872. comp.repaint(); // (needed when windows are un-minimised)
  873. else
  874. attach();
  875. }
  876. else
  877. {
  878. detach();
  879. }
  880. }
  881. using ComponentMovementWatcher::componentVisibilityChanged;
  882. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  883. void componentBeingDeleted (Component& c) override
  884. {
  885. /* You must call detach() or delete your OpenGLContext to remove it
  886. from a component BEFORE deleting the component that it is using!
  887. */
  888. jassertfalse;
  889. ComponentMovementWatcher::componentBeingDeleted (c);
  890. }
  891. #endif
  892. private:
  893. OpenGLContext& context;
  894. bool canBeAttached (const Component& comp) noexcept
  895. {
  896. return (! context.overrideCanAttach) && comp.getWidth() > 0 && comp.getHeight() > 0 && isShowingOrMinimised (comp);
  897. }
  898. static bool isShowingOrMinimised (const Component& c)
  899. {
  900. if (! c.isVisible())
  901. return false;
  902. if (auto* p = c.getParentComponent())
  903. return isShowingOrMinimised (*p);
  904. return c.getPeer() != nullptr;
  905. }
  906. static bool isAttached (const Component& comp) noexcept
  907. {
  908. return comp.getCachedComponentImage() != nullptr;
  909. }
  910. void attach()
  911. {
  912. auto& comp = *getComponent();
  913. auto* newCachedImage = new CachedImage (context, comp,
  914. context.openGLPixelFormat,
  915. context.contextToShareWith);
  916. comp.setCachedComponentImage (newCachedImage);
  917. start();
  918. }
  919. void stop()
  920. {
  921. stopTimer();
  922. auto& comp = *getComponent();
  923. #if JUCE_MAC
  924. [[(NSView*) comp.getWindowHandle() window] disableScreenUpdatesUntilFlush];
  925. #endif
  926. if (auto* oldCachedImage = CachedImage::get (comp))
  927. oldCachedImage->stop(); // (must stop this before detaching it from the component)
  928. }
  929. void start()
  930. {
  931. auto& comp = *getComponent();
  932. if (auto* cachedImage = CachedImage::get (comp))
  933. {
  934. cachedImage->start(); // (must wait until this is attached before starting its thread)
  935. cachedImage->updateViewportSize();
  936. startTimer (400);
  937. }
  938. }
  939. void timerCallback() override
  940. {
  941. if (auto* cachedImage = CachedImage::get (*getComponent()))
  942. cachedImage->checkViewportBounds();
  943. }
  944. };
  945. //==============================================================================
  946. OpenGLContext::OpenGLContext()
  947. {
  948. }
  949. OpenGLContext::~OpenGLContext()
  950. {
  951. detach();
  952. }
  953. void OpenGLContext::setRenderer (OpenGLRenderer* rendererToUse) noexcept
  954. {
  955. // This method must not be called when the context has already been attached!
  956. // Call it before attaching your context, or use detach() first, before calling this!
  957. jassert (nativeContext == nullptr);
  958. renderer = rendererToUse;
  959. }
  960. void OpenGLContext::setComponentPaintingEnabled (bool shouldPaintComponent) noexcept
  961. {
  962. // This method must not be called when the context has already been attached!
  963. // Call it before attaching your context, or use detach() first, before calling this!
  964. jassert (nativeContext == nullptr);
  965. renderComponents = shouldPaintComponent;
  966. }
  967. void OpenGLContext::setContinuousRepainting (bool shouldContinuouslyRepaint) noexcept
  968. {
  969. continuousRepaint = shouldContinuouslyRepaint;
  970. #if JUCE_MAC
  971. if (auto* component = getTargetComponent())
  972. {
  973. detach();
  974. attachment.reset (new Attachment (*this, *component));
  975. }
  976. #endif
  977. triggerRepaint();
  978. }
  979. void OpenGLContext::setPixelFormat (const OpenGLPixelFormat& preferredPixelFormat) noexcept
  980. {
  981. // This method must not be called when the context has already been attached!
  982. // Call it before attaching your context, or use detach() first, before calling this!
  983. jassert (nativeContext == nullptr);
  984. openGLPixelFormat = preferredPixelFormat;
  985. }
  986. void OpenGLContext::setTextureMagnificationFilter (OpenGLContext::TextureMagnificationFilter magFilterMode) noexcept
  987. {
  988. texMagFilter = magFilterMode;
  989. }
  990. void OpenGLContext::setNativeSharedContext (void* nativeContextToShareWith) noexcept
  991. {
  992. // This method must not be called when the context has already been attached!
  993. // Call it before attaching your context, or use detach() first, before calling this!
  994. jassert (nativeContext == nullptr);
  995. contextToShareWith = nativeContextToShareWith;
  996. }
  997. void OpenGLContext::setMultisamplingEnabled (bool b) noexcept
  998. {
  999. // This method must not be called when the context has already been attached!
  1000. // Call it before attaching your context, or use detach() first, before calling this!
  1001. jassert (nativeContext == nullptr);
  1002. useMultisampling = b;
  1003. }
  1004. void OpenGLContext::setOpenGLVersionRequired (OpenGLVersion v) noexcept
  1005. {
  1006. versionRequired = v;
  1007. }
  1008. void OpenGLContext::attachTo (Component& component)
  1009. {
  1010. component.repaint();
  1011. if (getTargetComponent() != &component)
  1012. {
  1013. detach();
  1014. attachment.reset (new Attachment (*this, component));
  1015. }
  1016. }
  1017. void OpenGLContext::detach()
  1018. {
  1019. if (auto* a = attachment.get())
  1020. {
  1021. a->detach(); // must detach before nulling our pointer
  1022. attachment.reset();
  1023. }
  1024. nativeContext = nullptr;
  1025. }
  1026. bool OpenGLContext::isAttached() const noexcept
  1027. {
  1028. return nativeContext != nullptr;
  1029. }
  1030. Component* OpenGLContext::getTargetComponent() const noexcept
  1031. {
  1032. return attachment != nullptr ? attachment->getComponent() : nullptr;
  1033. }
  1034. OpenGLContext* OpenGLContext::getContextAttachedTo (Component& c) noexcept
  1035. {
  1036. if (auto* ci = CachedImage::get (c))
  1037. return &(ci->context);
  1038. return nullptr;
  1039. }
  1040. static ThreadLocalValue<OpenGLContext*> currentThreadActiveContext;
  1041. OpenGLContext* OpenGLContext::getCurrentContext()
  1042. {
  1043. return currentThreadActiveContext.get();
  1044. }
  1045. bool OpenGLContext::makeActive() const noexcept
  1046. {
  1047. auto& current = currentThreadActiveContext.get();
  1048. if (nativeContext != nullptr && nativeContext->makeActive())
  1049. {
  1050. current = const_cast<OpenGLContext*> (this);
  1051. return true;
  1052. }
  1053. current = nullptr;
  1054. return false;
  1055. }
  1056. bool OpenGLContext::isActive() const noexcept
  1057. {
  1058. return nativeContext != nullptr && nativeContext->isActive();
  1059. }
  1060. void OpenGLContext::deactivateCurrentContext()
  1061. {
  1062. NativeContext::deactivateCurrentContext();
  1063. currentThreadActiveContext.get() = nullptr;
  1064. }
  1065. void OpenGLContext::triggerRepaint()
  1066. {
  1067. if (auto* cachedImage = getCachedImage())
  1068. cachedImage->triggerRepaint();
  1069. }
  1070. void OpenGLContext::swapBuffers()
  1071. {
  1072. if (nativeContext != nullptr)
  1073. nativeContext->swapBuffers();
  1074. }
  1075. unsigned int OpenGLContext::getFrameBufferID() const noexcept
  1076. {
  1077. return nativeContext != nullptr ? nativeContext->getFrameBufferID() : 0;
  1078. }
  1079. bool OpenGLContext::setSwapInterval (int numFramesPerSwap)
  1080. {
  1081. return nativeContext != nullptr && nativeContext->setSwapInterval (numFramesPerSwap);
  1082. }
  1083. int OpenGLContext::getSwapInterval() const
  1084. {
  1085. return nativeContext != nullptr ? nativeContext->getSwapInterval() : 0;
  1086. }
  1087. void* OpenGLContext::getRawContext() const noexcept
  1088. {
  1089. return nativeContext != nullptr ? nativeContext->getRawContext() : nullptr;
  1090. }
  1091. OpenGLContext::CachedImage* OpenGLContext::getCachedImage() const noexcept
  1092. {
  1093. if (auto* comp = getTargetComponent())
  1094. return CachedImage::get (*comp);
  1095. return nullptr;
  1096. }
  1097. bool OpenGLContext::areShadersAvailable() const
  1098. {
  1099. auto* c = getCachedImage();
  1100. return c != nullptr && c->shadersAvailable;
  1101. }
  1102. bool OpenGLContext::isTextureNpotSupported() const
  1103. {
  1104. auto* c = getCachedImage();
  1105. return c != nullptr && c->textureNpotSupported;
  1106. }
  1107. ReferenceCountedObject* OpenGLContext::getAssociatedObject (const char* name) const
  1108. {
  1109. jassert (name != nullptr);
  1110. auto* c = getCachedImage();
  1111. // This method must only be called from an openGL rendering callback.
  1112. jassert (c != nullptr && nativeContext != nullptr);
  1113. jassert (getCurrentContext() != nullptr);
  1114. auto index = c->associatedObjectNames.indexOf (name);
  1115. return index >= 0 ? c->associatedObjects.getUnchecked (index).get() : nullptr;
  1116. }
  1117. void OpenGLContext::setAssociatedObject (const char* name, ReferenceCountedObject* newObject)
  1118. {
  1119. jassert (name != nullptr);
  1120. if (auto* c = getCachedImage())
  1121. {
  1122. // This method must only be called from an openGL rendering callback.
  1123. jassert (nativeContext != nullptr);
  1124. jassert (getCurrentContext() != nullptr);
  1125. const int index = c->associatedObjectNames.indexOf (name);
  1126. if (index >= 0)
  1127. {
  1128. if (newObject != nullptr)
  1129. {
  1130. c->associatedObjects.set (index, newObject);
  1131. }
  1132. else
  1133. {
  1134. c->associatedObjectNames.remove (index);
  1135. c->associatedObjects.remove (index);
  1136. }
  1137. }
  1138. else if (newObject != nullptr)
  1139. {
  1140. c->associatedObjectNames.add (name);
  1141. c->associatedObjects.add (newObject);
  1142. }
  1143. }
  1144. }
  1145. void OpenGLContext::setImageCacheSize (size_t newSize) noexcept { imageCacheMaxSize = newSize; }
  1146. size_t OpenGLContext::getImageCacheSize() const noexcept { return imageCacheMaxSize; }
  1147. void OpenGLContext::execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock)
  1148. {
  1149. if (auto* c = getCachedImage())
  1150. c->execute (std::move (workerToUse), shouldBlock);
  1151. else
  1152. jassertfalse; // You must have attached the context to a component
  1153. }
  1154. //==============================================================================
  1155. struct DepthTestDisabler
  1156. {
  1157. DepthTestDisabler() noexcept
  1158. {
  1159. glGetBooleanv (GL_DEPTH_TEST, &wasEnabled);
  1160. if (wasEnabled)
  1161. glDisable (GL_DEPTH_TEST);
  1162. }
  1163. ~DepthTestDisabler() noexcept
  1164. {
  1165. if (wasEnabled)
  1166. glEnable (GL_DEPTH_TEST);
  1167. }
  1168. GLboolean wasEnabled;
  1169. };
  1170. //==============================================================================
  1171. void OpenGLContext::copyTexture (const Rectangle<int>& targetClipArea,
  1172. const Rectangle<int>& anchorPosAndTextureSize,
  1173. const int contextWidth, const int contextHeight,
  1174. bool flippedVertically)
  1175. {
  1176. if (contextWidth <= 0 || contextHeight <= 0)
  1177. return;
  1178. JUCE_CHECK_OPENGL_ERROR
  1179. glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  1180. glEnable (GL_BLEND);
  1181. DepthTestDisabler depthDisabler;
  1182. if (areShadersAvailable())
  1183. {
  1184. struct OverlayShaderProgram : public ReferenceCountedObject
  1185. {
  1186. OverlayShaderProgram (OpenGLContext& context)
  1187. : program (context), params (program)
  1188. {}
  1189. static const OverlayShaderProgram& select (OpenGLContext& context)
  1190. {
  1191. static const char programValueID[] = "juceGLComponentOverlayShader";
  1192. OverlayShaderProgram* program = static_cast<OverlayShaderProgram*> (context.getAssociatedObject (programValueID));
  1193. if (program == nullptr)
  1194. {
  1195. program = new OverlayShaderProgram (context);
  1196. context.setAssociatedObject (programValueID, program);
  1197. }
  1198. program->program.use();
  1199. return *program;
  1200. }
  1201. struct BuiltProgram : public OpenGLShaderProgram
  1202. {
  1203. explicit BuiltProgram (OpenGLContext& ctx)
  1204. : OpenGLShaderProgram (ctx)
  1205. {
  1206. addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (
  1207. "attribute " JUCE_HIGHP " vec2 position;"
  1208. "uniform " JUCE_HIGHP " vec2 screenSize;"
  1209. "uniform " JUCE_HIGHP " float textureBounds[4];"
  1210. "uniform " JUCE_HIGHP " vec2 vOffsetAndScale;"
  1211. "varying " JUCE_HIGHP " vec2 texturePos;"
  1212. "void main()"
  1213. "{"
  1214. JUCE_HIGHP " vec2 scaled = position / (0.5 * screenSize.xy);"
  1215. "gl_Position = vec4 (scaled.x - 1.0, 1.0 - scaled.y, 0, 1.0);"
  1216. "texturePos = (position - vec2 (textureBounds[0], textureBounds[1])) / vec2 (textureBounds[2], textureBounds[3]);"
  1217. "texturePos = vec2 (texturePos.x, vOffsetAndScale.x + vOffsetAndScale.y * texturePos.y);"
  1218. "}"));
  1219. addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (
  1220. "uniform sampler2D imageTexture;"
  1221. "varying " JUCE_HIGHP " vec2 texturePos;"
  1222. "void main()"
  1223. "{"
  1224. "gl_FragColor = texture2D (imageTexture, texturePos);"
  1225. "}"));
  1226. link();
  1227. }
  1228. };
  1229. struct Params
  1230. {
  1231. Params (OpenGLShaderProgram& prog)
  1232. : positionAttribute (prog, "position"),
  1233. screenSize (prog, "screenSize"),
  1234. imageTexture (prog, "imageTexture"),
  1235. textureBounds (prog, "textureBounds"),
  1236. vOffsetAndScale (prog, "vOffsetAndScale")
  1237. {}
  1238. void set (const float targetWidth, const float targetHeight, const Rectangle<float>& bounds, bool flipVertically) const
  1239. {
  1240. const GLfloat m[] = { bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight() };
  1241. textureBounds.set (m, 4);
  1242. imageTexture.set (0);
  1243. screenSize.set (targetWidth, targetHeight);
  1244. vOffsetAndScale.set (flipVertically ? 0.0f : 1.0f,
  1245. flipVertically ? 1.0f : -1.0f);
  1246. }
  1247. OpenGLShaderProgram::Attribute positionAttribute;
  1248. OpenGLShaderProgram::Uniform screenSize, imageTexture, textureBounds, vOffsetAndScale;
  1249. };
  1250. BuiltProgram program;
  1251. Params params;
  1252. };
  1253. auto left = (GLshort) targetClipArea.getX();
  1254. auto top = (GLshort) targetClipArea.getY();
  1255. auto right = (GLshort) targetClipArea.getRight();
  1256. auto bottom = (GLshort) targetClipArea.getBottom();
  1257. const GLshort vertices[] = { left, bottom, right, bottom, left, top, right, top };
  1258. auto& program = OverlayShaderProgram::select (*this);
  1259. program.params.set ((float) contextWidth, (float) contextHeight, anchorPosAndTextureSize.toFloat(), flippedVertically);
  1260. GLuint vertexBuffer = 0;
  1261. extensions.glGenBuffers (1, &vertexBuffer);
  1262. extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
  1263. extensions.glBufferData (GL_ARRAY_BUFFER, sizeof (vertices), vertices, GL_STATIC_DRAW);
  1264. auto index = (GLuint) program.params.positionAttribute.attributeID;
  1265. extensions.glVertexAttribPointer (index, 2, GL_SHORT, GL_FALSE, 4, nullptr);
  1266. extensions.glEnableVertexAttribArray (index);
  1267. JUCE_CHECK_OPENGL_ERROR
  1268. if (extensions.glCheckFramebufferStatus (GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
  1269. {
  1270. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  1271. extensions.glBindBuffer (GL_ARRAY_BUFFER, 0);
  1272. extensions.glUseProgram (0);
  1273. extensions.glDisableVertexAttribArray (index);
  1274. extensions.glDeleteBuffers (1, &vertexBuffer);
  1275. }
  1276. else
  1277. {
  1278. clearGLError();
  1279. }
  1280. }
  1281. else
  1282. {
  1283. jassert (attachment == nullptr); // Running on an old graphics card!
  1284. }
  1285. JUCE_CHECK_OPENGL_ERROR
  1286. }
  1287. #if JUCE_ANDROID
  1288. void OpenGLContext::NativeContext::surfaceCreated (LocalRef<jobject>)
  1289. {
  1290. {
  1291. const std::lock_guard lock { nativeHandleMutex };
  1292. jassert (hasInitialised);
  1293. // has the context already attached?
  1294. jassert (surface.get() == EGL_NO_SURFACE && context.get() == EGL_NO_CONTEXT);
  1295. const auto window = getNativeWindow();
  1296. if (window == nullptr)
  1297. {
  1298. // failed to get a pointer to the native window so bail out
  1299. jassertfalse;
  1300. return;
  1301. }
  1302. // create the surface
  1303. surface.reset (eglCreateWindowSurface (display, config, window.get(), nullptr));
  1304. jassert (surface.get() != EGL_NO_SURFACE);
  1305. // create the OpenGL context
  1306. EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
  1307. context.reset (eglCreateContext (display, config, EGL_NO_CONTEXT, contextAttribs));
  1308. jassert (context.get() != EGL_NO_CONTEXT);
  1309. }
  1310. if (auto* cached = CachedImage::get (component))
  1311. {
  1312. cached->resume();
  1313. cached->triggerRepaint();
  1314. }
  1315. }
  1316. void OpenGLContext::NativeContext::surfaceDestroyed (LocalRef<jobject>)
  1317. {
  1318. if (auto* cached = CachedImage::get (component))
  1319. cached->pause();
  1320. {
  1321. const std::lock_guard lock { nativeHandleMutex };
  1322. context.reset (EGL_NO_CONTEXT);
  1323. surface.reset (EGL_NO_SURFACE);
  1324. }
  1325. }
  1326. #endif
  1327. } // namespace juce