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.

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