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.

920 lines
29KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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. class OpenGLContext::CachedImage : public CachedComponentImage,
  18. public Thread
  19. {
  20. public:
  21. CachedImage (OpenGLContext& c, Component& comp,
  22. const OpenGLPixelFormat& pixFormat, void* contextToShare)
  23. : Thread ("OpenGL Rendering"),
  24. context (c), component (comp),
  25. scale (1.0),
  26. #if JUCE_OPENGL3
  27. vertexArrayObject (0),
  28. #endif
  29. #if JUCE_OPENGL_ES
  30. shadersAvailable (true),
  31. #else
  32. shadersAvailable (false),
  33. #endif
  34. hasInitialised (false),
  35. needsUpdate (1), lastMMLockReleaseTime (0)
  36. {
  37. nativeContext = new NativeContext (component, pixFormat, contextToShare,
  38. c.useMultisampling, c.versionRequired);
  39. if (nativeContext->createdOk())
  40. context.nativeContext = nativeContext;
  41. else
  42. nativeContext = nullptr;
  43. }
  44. ~CachedImage()
  45. {
  46. stop();
  47. }
  48. void start()
  49. {
  50. #if ! JUCE_ANDROID
  51. if (nativeContext != nullptr)
  52. startThread (6);
  53. #endif
  54. }
  55. void stop()
  56. {
  57. #if ! JUCE_ANDROID
  58. stopThread (10000);
  59. #endif
  60. hasInitialised = false;
  61. }
  62. //==============================================================================
  63. void paint (Graphics&) override {}
  64. bool invalidateAll() override
  65. {
  66. validArea.clear();
  67. triggerRepaint();
  68. return false;
  69. }
  70. bool invalidate (const Rectangle<int>& area) override
  71. {
  72. validArea.subtract (area * scale);
  73. triggerRepaint();
  74. return false;
  75. }
  76. void releaseResources() override {}
  77. void triggerRepaint()
  78. {
  79. needsUpdate = 1;
  80. #if JUCE_ANDROID
  81. if (nativeContext != nullptr)
  82. nativeContext->triggerRepaint();
  83. #else
  84. notify();
  85. #endif
  86. }
  87. //==============================================================================
  88. bool ensureFrameBufferSize()
  89. {
  90. const int fbW = cachedImageFrameBuffer.getWidth();
  91. const int fbH = cachedImageFrameBuffer.getHeight();
  92. if (fbW != viewportArea.getWidth() || fbH != viewportArea.getHeight() || ! cachedImageFrameBuffer.isValid())
  93. {
  94. if (! cachedImageFrameBuffer.initialise (context, viewportArea.getWidth(), viewportArea.getHeight()))
  95. return false;
  96. validArea.clear();
  97. JUCE_CHECK_OPENGL_ERROR
  98. }
  99. return true;
  100. }
  101. void clearRegionInFrameBuffer (const RectangleList<int>& list)
  102. {
  103. glClearColor (0, 0, 0, 0);
  104. glEnable (GL_SCISSOR_TEST);
  105. const GLuint previousFrameBufferTarget = OpenGLFrameBuffer::getCurrentFrameBufferTarget();
  106. cachedImageFrameBuffer.makeCurrentRenderingTarget();
  107. const int imageH = cachedImageFrameBuffer.getHeight();
  108. for (const Rectangle<int>* i = list.begin(), * const e = list.end(); i != e; ++i)
  109. {
  110. glScissor (i->getX(), imageH - i->getBottom(), i->getWidth(), i->getHeight());
  111. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  112. }
  113. glDisable (GL_SCISSOR_TEST);
  114. context.extensions.glBindFramebuffer (GL_FRAMEBUFFER, previousFrameBufferTarget);
  115. JUCE_CHECK_OPENGL_ERROR
  116. }
  117. bool renderFrame()
  118. {
  119. ScopedPointer<MessageManagerLock> mmLock;
  120. const Rectangle<int> screenBounds (component.getTopLevelComponent()->getScreenBounds());
  121. if (lastScreenBounds != screenBounds)
  122. updateViewportSize (false);
  123. const bool isUpdating = needsUpdate.compareAndSetBool (0, 1);
  124. if (context.renderComponents && isUpdating)
  125. {
  126. // This avoids hogging the message thread when doing intensive rendering.
  127. if (lastMMLockReleaseTime + 1 >= Time::getMillisecondCounter())
  128. wait (2);
  129. mmLock = new MessageManagerLock (this); // need to acquire this before locking the context.
  130. if (! mmLock->lockWasGained())
  131. return false;
  132. }
  133. if (! context.makeActive())
  134. return false;
  135. NativeContext::Locker locker (*nativeContext);
  136. JUCE_CHECK_OPENGL_ERROR
  137. if (context.renderer != nullptr)
  138. {
  139. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  140. context.currentRenderScale = scale;
  141. context.renderer->renderOpenGL();
  142. clearGLError();
  143. }
  144. if (context.renderComponents)
  145. {
  146. if (isUpdating)
  147. {
  148. paintComponent();
  149. mmLock = nullptr;
  150. lastMMLockReleaseTime = Time::getMillisecondCounter();
  151. }
  152. glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight());
  153. drawComponentBuffer();
  154. }
  155. context.swapBuffers();
  156. return true;
  157. }
  158. void updateViewportSize (bool canTriggerUpdate)
  159. {
  160. if (ComponentPeer* peer = component.getPeer())
  161. {
  162. lastScreenBounds = component.getTopLevelComponent()->getScreenBounds();
  163. const double newScale = Desktop::getInstance().getDisplays()
  164. .getDisplayContaining (lastScreenBounds.getCentre()).scale;
  165. Rectangle<int> newArea (peer->getComponent().getLocalArea (&component, component.getLocalBounds())
  166. .withZeroOrigin()
  167. * newScale);
  168. if (scale != newScale || viewportArea != newArea)
  169. {
  170. scale = newScale;
  171. viewportArea = newArea;
  172. if (canTriggerUpdate)
  173. invalidateAll();
  174. }
  175. }
  176. }
  177. void paintComponent()
  178. {
  179. // you mustn't set your own cached image object when attaching a GL context!
  180. jassert (get (component) == this);
  181. updateViewportSize (false);
  182. if (! ensureFrameBufferSize())
  183. return;
  184. RectangleList<int> invalid (viewportArea);
  185. invalid.subtract (validArea);
  186. validArea = viewportArea;
  187. if (! invalid.isEmpty())
  188. {
  189. clearRegionInFrameBuffer (invalid);
  190. {
  191. ScopedPointer<LowLevelGraphicsContext> g (createOpenGLGraphicsContext (context, cachedImageFrameBuffer));
  192. g->clipToRectangleList (invalid);
  193. g->addTransform (AffineTransform::scale ((float) scale));
  194. paintOwner (*g);
  195. JUCE_CHECK_OPENGL_ERROR
  196. }
  197. if (! context.isActive())
  198. context.makeActive();
  199. }
  200. JUCE_CHECK_OPENGL_ERROR
  201. }
  202. void drawComponentBuffer()
  203. {
  204. #if ! JUCE_ANDROID
  205. glEnable (GL_TEXTURE_2D);
  206. clearGLError();
  207. #endif
  208. context.extensions.glActiveTexture (GL_TEXTURE0);
  209. glBindTexture (GL_TEXTURE_2D, cachedImageFrameBuffer.getTextureID());
  210. const Rectangle<int> cacheBounds (cachedImageFrameBuffer.getWidth(), cachedImageFrameBuffer.getHeight());
  211. context.copyTexture (cacheBounds, cacheBounds, cacheBounds.getWidth(), cacheBounds.getHeight(), false);
  212. glBindTexture (GL_TEXTURE_2D, 0);
  213. JUCE_CHECK_OPENGL_ERROR
  214. }
  215. void paintOwner (LowLevelGraphicsContext& llgc)
  216. {
  217. Graphics g (llgc);
  218. #if JUCE_ENABLE_REPAINT_DEBUGGING
  219. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  220. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  221. #endif
  222. {
  223. g.saveState();
  224. }
  225. #endif
  226. JUCE_TRY
  227. {
  228. component.paintEntireComponent (g, false);
  229. }
  230. JUCE_CATCH_EXCEPTION
  231. #if JUCE_ENABLE_REPAINT_DEBUGGING
  232. #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE
  233. if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE)
  234. #endif
  235. {
  236. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  237. // clearly when things are being repainted.
  238. g.restoreState();
  239. static Random rng;
  240. g.fillAll (Colour ((uint8) rng.nextInt (255),
  241. (uint8) rng.nextInt (255),
  242. (uint8) rng.nextInt (255),
  243. (uint8) 0x50));
  244. }
  245. #endif
  246. }
  247. void handleResize()
  248. {
  249. updateViewportSize (true);
  250. #if JUCE_MAC
  251. if (hasInitialised)
  252. {
  253. [nativeContext->view update];
  254. renderFrame();
  255. }
  256. #endif
  257. }
  258. //==============================================================================
  259. void run() override
  260. {
  261. {
  262. // Allow the message thread to finish setting-up the context before using it..
  263. MessageManagerLock mml (this);
  264. if (! mml.lockWasGained())
  265. return;
  266. }
  267. initialiseOnThread();
  268. hasInitialised = true;
  269. while (! threadShouldExit())
  270. {
  271. if (! renderFrame())
  272. wait (5); // failed to render, so avoid a tight fail-loop.
  273. else if (! context.continuousRepaint)
  274. wait (-1);
  275. }
  276. shutdownOnThread();
  277. }
  278. void initialiseOnThread()
  279. {
  280. // On android, this can get called twice, so drop any previous state..
  281. associatedObjectNames.clear();
  282. associatedObjects.clear();
  283. cachedImageFrameBuffer.release();
  284. context.makeActive();
  285. nativeContext->initialiseOnRenderThread (context);
  286. #if JUCE_OPENGL3
  287. if (OpenGLShaderProgram::getLanguageVersion() > 1.2)
  288. {
  289. glGenVertexArrays (1, &vertexArrayObject);
  290. glBindVertexArray (vertexArrayObject);
  291. }
  292. #endif
  293. glViewport (0, 0, component.getWidth(), component.getHeight());
  294. context.extensions.initialise();
  295. nativeContext->setSwapInterval (1);
  296. #if ! JUCE_OPENGL_ES
  297. shadersAvailable = OpenGLShaderProgram::getLanguageVersion() > 0;
  298. #endif
  299. if (context.renderer != nullptr)
  300. context.renderer->newOpenGLContextCreated();
  301. }
  302. void shutdownOnThread()
  303. {
  304. if (context.renderer != nullptr)
  305. context.renderer->openGLContextClosing();
  306. #if JUCE_OPENGL3
  307. if (vertexArrayObject != 0)
  308. glDeleteVertexArrays (1, &vertexArrayObject);
  309. #endif
  310. cachedImageFrameBuffer.release();
  311. nativeContext->shutdownOnRenderThread();
  312. associatedObjectNames.clear();
  313. associatedObjects.clear();
  314. }
  315. //==============================================================================
  316. static CachedImage* get (Component& c) noexcept
  317. {
  318. return dynamic_cast<CachedImage*> (c.getCachedComponentImage());
  319. }
  320. //==============================================================================
  321. ScopedPointer<NativeContext> nativeContext;
  322. OpenGLContext& context;
  323. Component& component;
  324. OpenGLFrameBuffer cachedImageFrameBuffer;
  325. RectangleList<int> validArea;
  326. Rectangle<int> viewportArea, lastScreenBounds;
  327. double scale;
  328. #if JUCE_OPENGL3
  329. GLuint vertexArrayObject;
  330. #endif
  331. StringArray associatedObjectNames;
  332. ReferenceCountedArray<ReferenceCountedObject> associatedObjects;
  333. WaitableEvent canPaintNowFlag, finishedPaintingFlag;
  334. bool shadersAvailable, hasInitialised;
  335. Atomic<int> needsUpdate;
  336. uint32 lastMMLockReleaseTime;
  337. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedImage)
  338. };
  339. //==============================================================================
  340. #if JUCE_ANDROID
  341. void OpenGLContext::NativeContext::contextCreatedCallback()
  342. {
  343. isInsideGLCallback = true;
  344. if (CachedImage* const c = CachedImage::get (component))
  345. c->initialiseOnThread();
  346. else
  347. jassertfalse;
  348. isInsideGLCallback = false;
  349. }
  350. void OpenGLContext::NativeContext::renderCallback()
  351. {
  352. isInsideGLCallback = true;
  353. if (CachedImage* const c = CachedImage::get (component))
  354. {
  355. if (c->context.continuousRepaint)
  356. c->context.triggerRepaint();
  357. c->renderFrame();
  358. }
  359. isInsideGLCallback = false;
  360. }
  361. #endif
  362. //==============================================================================
  363. class OpenGLContext::Attachment : public ComponentMovementWatcher
  364. {
  365. public:
  366. Attachment (OpenGLContext& c, Component& comp)
  367. : ComponentMovementWatcher (&comp), context (c)
  368. {
  369. if (canBeAttached (comp))
  370. attach();
  371. }
  372. ~Attachment()
  373. {
  374. detach();
  375. }
  376. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) override
  377. {
  378. Component& comp = *getComponent();
  379. if (isAttached (comp) != canBeAttached (comp))
  380. componentVisibilityChanged();
  381. if (comp.getWidth() > 0 && comp.getHeight() > 0
  382. && context.nativeContext != nullptr)
  383. {
  384. if (CachedImage* const c = CachedImage::get (comp))
  385. c->handleResize();
  386. if (ComponentPeer* peer = comp.getTopLevelComponent()->getPeer())
  387. context.nativeContext->updateWindowPosition (peer->getAreaCoveredBy (comp));
  388. }
  389. }
  390. void componentPeerChanged() override
  391. {
  392. detach();
  393. componentVisibilityChanged();
  394. }
  395. void componentVisibilityChanged() override
  396. {
  397. Component& comp = *getComponent();
  398. if (canBeAttached (comp))
  399. {
  400. if (! isAttached (comp))
  401. attach();
  402. }
  403. else
  404. {
  405. detach();
  406. }
  407. }
  408. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  409. void componentBeingDeleted (Component& c) override
  410. {
  411. /* You must call detach() or delete your OpenGLContext to remove it
  412. from a component BEFORE deleting the component that it is using!
  413. */
  414. jassertfalse;
  415. ComponentMovementWatcher::componentBeingDeleted (c);
  416. }
  417. #endif
  418. private:
  419. OpenGLContext& context;
  420. static bool canBeAttached (const Component& comp) noexcept
  421. {
  422. return comp.getWidth() > 0 && comp.getHeight() > 0 && isShowingOrMinimised (comp);
  423. }
  424. static bool isShowingOrMinimised (const Component& c)
  425. {
  426. if (! c.isVisible())
  427. return false;
  428. if (Component* p = c.getParentComponent())
  429. return isShowingOrMinimised (*p);
  430. return c.getPeer() != nullptr;
  431. }
  432. static bool isAttached (const Component& comp) noexcept
  433. {
  434. return comp.getCachedComponentImage() != nullptr;
  435. }
  436. void attach()
  437. {
  438. Component& comp = *getComponent();
  439. CachedImage* const newCachedImage = new CachedImage (context, comp,
  440. context.pixelFormat,
  441. context.contextToShareWith);
  442. comp.setCachedComponentImage (newCachedImage);
  443. newCachedImage->start(); // (must wait until this is attached before starting its thread)
  444. newCachedImage->updateViewportSize (true);
  445. }
  446. void detach()
  447. {
  448. Component& comp = *getComponent();
  449. #if JUCE_MAC
  450. [[(NSView*) comp.getWindowHandle() window] disableScreenUpdatesUntilFlush];
  451. #endif
  452. if (CachedImage* const oldCachedImage = CachedImage::get (comp))
  453. oldCachedImage->stop(); // (must stop this before detaching it from the component)
  454. comp.setCachedComponentImage (nullptr);
  455. context.nativeContext = nullptr;
  456. }
  457. };
  458. //==============================================================================
  459. OpenGLContext::OpenGLContext()
  460. : nativeContext (nullptr), renderer (nullptr), currentRenderScale (1.0),
  461. contextToShareWith (nullptr), versionRequired (OpenGLContext::defaultGLVersion),
  462. renderComponents (true), useMultisampling (false), continuousRepaint (false)
  463. {
  464. }
  465. OpenGLContext::~OpenGLContext()
  466. {
  467. detach();
  468. }
  469. void OpenGLContext::setRenderer (OpenGLRenderer* rendererToUse) noexcept
  470. {
  471. // This method must not be called when the context has already been attached!
  472. // Call it before attaching your context, or use detach() first, before calling this!
  473. jassert (nativeContext == nullptr);
  474. renderer = rendererToUse;
  475. }
  476. void OpenGLContext::setComponentPaintingEnabled (bool shouldPaintComponent) noexcept
  477. {
  478. // This method must not be called when the context has already been attached!
  479. // Call it before attaching your context, or use detach() first, before calling this!
  480. jassert (nativeContext == nullptr);
  481. renderComponents = shouldPaintComponent;
  482. }
  483. void OpenGLContext::setContinuousRepainting (bool shouldContinuouslyRepaint) noexcept
  484. {
  485. continuousRepaint = shouldContinuouslyRepaint;
  486. }
  487. void OpenGLContext::setPixelFormat (const OpenGLPixelFormat& preferredPixelFormat) noexcept
  488. {
  489. // This method must not be called when the context has already been attached!
  490. // Call it before attaching your context, or use detach() first, before calling this!
  491. jassert (nativeContext == nullptr);
  492. pixelFormat = preferredPixelFormat;
  493. }
  494. void OpenGLContext::setNativeSharedContext (void* nativeContextToShareWith) noexcept
  495. {
  496. // This method must not be called when the context has already been attached!
  497. // Call it before attaching your context, or use detach() first, before calling this!
  498. jassert (nativeContext == nullptr);
  499. contextToShareWith = nativeContextToShareWith;
  500. }
  501. void OpenGLContext::setMultisamplingEnabled (bool b) noexcept
  502. {
  503. // This method must not be called when the context has already been attached!
  504. // Call it before attaching your context, or use detach() first, before calling this!
  505. jassert (nativeContext == nullptr);
  506. useMultisampling = b;
  507. }
  508. void OpenGLContext::setOpenGLVersionRequired (OpenGLVersion v) noexcept
  509. {
  510. versionRequired = v;
  511. }
  512. void OpenGLContext::attachTo (Component& component)
  513. {
  514. component.repaint();
  515. if (getTargetComponent() != &component)
  516. {
  517. detach();
  518. attachment = new Attachment (*this, component);
  519. }
  520. }
  521. void OpenGLContext::detach()
  522. {
  523. attachment = nullptr;
  524. nativeContext = nullptr;
  525. }
  526. bool OpenGLContext::isAttached() const noexcept
  527. {
  528. return nativeContext != nullptr;
  529. }
  530. Component* OpenGLContext::getTargetComponent() const noexcept
  531. {
  532. return attachment != nullptr ? attachment->getComponent() : nullptr;
  533. }
  534. static ThreadLocalValue<OpenGLContext*> currentThreadActiveContext;
  535. OpenGLContext* OpenGLContext::getCurrentContext()
  536. {
  537. return currentThreadActiveContext.get();
  538. }
  539. bool OpenGLContext::makeActive() const noexcept
  540. {
  541. OpenGLContext*& current = currentThreadActiveContext.get();
  542. if (nativeContext != nullptr && nativeContext->makeActive())
  543. {
  544. current = const_cast<OpenGLContext*> (this);
  545. return true;
  546. }
  547. current = nullptr;
  548. return false;
  549. }
  550. bool OpenGLContext::isActive() const noexcept
  551. {
  552. return nativeContext != nullptr && nativeContext->isActive();
  553. }
  554. void OpenGLContext::deactivateCurrentContext()
  555. {
  556. NativeContext::deactivateCurrentContext();
  557. currentThreadActiveContext.get() = nullptr;
  558. }
  559. void OpenGLContext::triggerRepaint()
  560. {
  561. if (CachedImage* const cachedImage = getCachedImage())
  562. cachedImage->triggerRepaint();
  563. }
  564. void OpenGLContext::swapBuffers()
  565. {
  566. if (nativeContext != nullptr)
  567. nativeContext->swapBuffers();
  568. }
  569. unsigned int OpenGLContext::getFrameBufferID() const noexcept
  570. {
  571. return nativeContext != nullptr ? nativeContext->getFrameBufferID() : 0;
  572. }
  573. bool OpenGLContext::setSwapInterval (int numFramesPerSwap)
  574. {
  575. return nativeContext != nullptr && nativeContext->setSwapInterval (numFramesPerSwap);
  576. }
  577. int OpenGLContext::getSwapInterval() const
  578. {
  579. return nativeContext != nullptr ? nativeContext->getSwapInterval() : 0;
  580. }
  581. void* OpenGLContext::getRawContext() const noexcept
  582. {
  583. return nativeContext != nullptr ? nativeContext->getRawContext() : nullptr;
  584. }
  585. OpenGLContext::CachedImage* OpenGLContext::getCachedImage() const noexcept
  586. {
  587. if (Component* const comp = getTargetComponent())
  588. return CachedImage::get (*comp);
  589. return nullptr;
  590. }
  591. bool OpenGLContext::areShadersAvailable() const
  592. {
  593. CachedImage* const c = getCachedImage();
  594. return c != nullptr && c->shadersAvailable;
  595. }
  596. ReferenceCountedObject* OpenGLContext::getAssociatedObject (const char* name) const
  597. {
  598. jassert (name != nullptr);
  599. CachedImage* const c = getCachedImage();
  600. // This method must only be called from an openGL rendering callback.
  601. jassert (c != nullptr && nativeContext != nullptr);
  602. jassert (getCurrentContext() != nullptr);
  603. const int index = c->associatedObjectNames.indexOf (name);
  604. return index >= 0 ? c->associatedObjects.getUnchecked (index) : nullptr;
  605. }
  606. void OpenGLContext::setAssociatedObject (const char* name, ReferenceCountedObject* newObject)
  607. {
  608. jassert (name != nullptr);
  609. if (CachedImage* const c = getCachedImage())
  610. {
  611. // This method must only be called from an openGL rendering callback.
  612. jassert (nativeContext != nullptr);
  613. jassert (getCurrentContext() != nullptr);
  614. const int index = c->associatedObjectNames.indexOf (name);
  615. if (index >= 0)
  616. {
  617. if (newObject != nullptr)
  618. {
  619. c->associatedObjects.set (index, newObject);
  620. }
  621. else
  622. {
  623. c->associatedObjectNames.remove (index);
  624. c->associatedObjects.remove (index);
  625. }
  626. }
  627. else if (newObject != nullptr)
  628. {
  629. c->associatedObjectNames.add (name);
  630. c->associatedObjects.add (newObject);
  631. }
  632. }
  633. }
  634. void OpenGLContext::copyTexture (const Rectangle<int>& targetClipArea,
  635. const Rectangle<int>& anchorPosAndTextureSize,
  636. const int contextWidth, const int contextHeight,
  637. bool flippedVertically)
  638. {
  639. if (contextWidth <= 0 || contextHeight <= 0)
  640. return;
  641. JUCE_CHECK_OPENGL_ERROR
  642. glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  643. glEnable (GL_BLEND);
  644. if (areShadersAvailable())
  645. {
  646. struct OverlayShaderProgram : public ReferenceCountedObject
  647. {
  648. OverlayShaderProgram (OpenGLContext& context)
  649. : program (context), builder (program), params (program)
  650. {}
  651. static const OverlayShaderProgram& select (OpenGLContext& context)
  652. {
  653. static const char programValueID[] = "juceGLComponentOverlayShader";
  654. OverlayShaderProgram* program = static_cast <OverlayShaderProgram*> (context.getAssociatedObject (programValueID));
  655. if (program == nullptr)
  656. {
  657. program = new OverlayShaderProgram (context);
  658. context.setAssociatedObject (programValueID, program);
  659. }
  660. program->program.use();
  661. return *program;
  662. }
  663. struct ProgramBuilder
  664. {
  665. ProgramBuilder (OpenGLShaderProgram& prog)
  666. {
  667. prog.addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (
  668. "attribute " JUCE_HIGHP " vec2 position;"
  669. "uniform " JUCE_HIGHP " vec2 screenSize;"
  670. "varying " JUCE_HIGHP " vec2 pixelPos;"
  671. "void main()"
  672. "{"
  673. "pixelPos = position;"
  674. JUCE_HIGHP " vec2 scaled = position / (0.5 * screenSize.xy);"
  675. "gl_Position = vec4 (scaled.x - 1.0, 1.0 - scaled.y, 0, 1.0);"
  676. "}"));
  677. prog.addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (
  678. "uniform sampler2D imageTexture;"
  679. "uniform " JUCE_HIGHP " float textureBounds[4];"
  680. "uniform " JUCE_HIGHP " vec2 vOffsetAndScale;"
  681. "varying " JUCE_HIGHP " vec2 pixelPos;"
  682. "void main()"
  683. "{"
  684. JUCE_HIGHP " vec2 texturePos = (pixelPos - vec2 (textureBounds[0], textureBounds[1]))"
  685. "/ vec2 (textureBounds[2], textureBounds[3]);"
  686. "gl_FragColor = texture2D (imageTexture, vec2 (texturePos.x, vOffsetAndScale.x + vOffsetAndScale.y * texturePos.y));"
  687. "}"));
  688. prog.link();
  689. }
  690. };
  691. struct Params
  692. {
  693. Params (OpenGLShaderProgram& prog)
  694. : positionAttribute (prog, "position"),
  695. screenSize (prog, "screenSize"),
  696. imageTexture (prog, "imageTexture"),
  697. textureBounds (prog, "textureBounds"),
  698. vOffsetAndScale (prog, "vOffsetAndScale")
  699. {}
  700. void set (const float targetWidth, const float targetHeight, const Rectangle<float>& bounds, bool flipVertically) const
  701. {
  702. const GLfloat m[] = { bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight() };
  703. textureBounds.set (m, 4);
  704. imageTexture.set (0);
  705. screenSize.set (targetWidth, targetHeight);
  706. vOffsetAndScale.set (flipVertically ? 0.0f : 1.0f,
  707. flipVertically ? 1.0f : -1.0f);
  708. }
  709. OpenGLShaderProgram::Attribute positionAttribute;
  710. OpenGLShaderProgram::Uniform screenSize, imageTexture, textureBounds, vOffsetAndScale;
  711. };
  712. OpenGLShaderProgram program;
  713. ProgramBuilder builder;
  714. Params params;
  715. };
  716. const GLshort left = (GLshort) targetClipArea.getX();
  717. const GLshort top = (GLshort) targetClipArea.getY();
  718. const GLshort right = (GLshort) targetClipArea.getRight();
  719. const GLshort bottom = (GLshort) targetClipArea.getBottom();
  720. const GLshort vertices[] = { left, bottom, right, bottom, left, top, right, top };
  721. const OverlayShaderProgram& program = OverlayShaderProgram::select (*this);
  722. program.params.set ((float) contextWidth, (float) contextHeight, anchorPosAndTextureSize.toFloat(), flippedVertically);
  723. GLuint vertexBuffer = 0;
  724. extensions.glGenBuffers (1, &vertexBuffer);
  725. extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
  726. extensions.glBufferData (GL_ARRAY_BUFFER, sizeof (vertices), vertices, GL_STATIC_DRAW);
  727. const GLuint index = (GLuint) program.params.positionAttribute.attributeID;
  728. extensions.glVertexAttribPointer (index, 2, GL_SHORT, GL_FALSE, 4, 0);
  729. extensions.glEnableVertexAttribArray (index);
  730. JUCE_CHECK_OPENGL_ERROR
  731. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  732. extensions.glBindBuffer (GL_ARRAY_BUFFER, 0);
  733. extensions.glUseProgram (0);
  734. extensions.glDisableVertexAttribArray (index);
  735. extensions.glDeleteBuffers (1, &vertexBuffer);
  736. }
  737. else
  738. {
  739. jassert (attachment == nullptr); // Running on an old graphics card!
  740. }
  741. JUCE_CHECK_OPENGL_ERROR
  742. }