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.

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