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.

888 lines
28KB

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