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.

358 lines
16KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. class OpenGLTexture;
  16. //==============================================================================
  17. /**
  18. Creates an OpenGL context, which can be attached to a component.
  19. To render some OpenGL, you should create an instance of an OpenGLContext,
  20. and call attachTo() to make it use a component as its render target.
  21. To provide threaded rendering, you can supply an OpenGLRenderer object that
  22. will be used to render each frame.
  23. Before your target component or OpenGLRenderer is deleted, you MUST call
  24. detach() or delete the OpenGLContext to allow the background thread to
  25. stop and the native resources to be freed safely.
  26. @see OpenGLRenderer
  27. @tags{OpenGL}
  28. */
  29. class JUCE_API OpenGLContext
  30. {
  31. public:
  32. OpenGLContext();
  33. /** Destructor. */
  34. ~OpenGLContext();
  35. //==============================================================================
  36. /** Gives the context an OpenGLRenderer to use to do the drawing.
  37. The object that you give it will not be owned by the context, so it's the caller's
  38. responsibility to manage its lifetime and make sure that it doesn't get deleted
  39. while the context may be using it. To stop the context using a renderer, just call
  40. this method with a null pointer.
  41. Note: This must be called BEFORE attaching your context to a target component!
  42. */
  43. void setRenderer (OpenGLRenderer*) noexcept;
  44. /** Attaches the context to a target component.
  45. If the component is not fully visible, this call will wait until the component
  46. is shown before actually creating a native context for it.
  47. When a native context is created, a thread is started, and will be used to call
  48. the OpenGLRenderer methods. The context will be floated above the target component,
  49. and when the target moves, it will track it. If the component is hidden/shown, the
  50. context may be deleted and re-created.
  51. */
  52. void attachTo (Component&);
  53. /** Detaches the context from its target component and deletes any native resources.
  54. If the context has not been attached, this will do nothing. Otherwise, it will block
  55. until the context and its thread have been cleaned up.
  56. */
  57. void detach();
  58. /** Returns true if the context is attached to a component and is on-screen.
  59. Note that if you call attachTo() for a non-visible component, this method will
  60. return false until the component is made visible.
  61. */
  62. bool isAttached() const noexcept;
  63. /** Returns the component to which this context is currently attached, or nullptr. */
  64. Component* getTargetComponent() const noexcept;
  65. /** If the given component has an OpenGLContext attached, then this will return it. */
  66. static OpenGLContext* getContextAttachedTo (Component& component) noexcept;
  67. //==============================================================================
  68. /** Sets the pixel format which you'd like to use for the target GL surface.
  69. Note: This must be called BEFORE attaching your context to a target component!
  70. */
  71. void setPixelFormat (const OpenGLPixelFormat& preferredPixelFormat) noexcept;
  72. /** Texture magnification filters, used by setTextureMagnificationFilter(). */
  73. enum TextureMagnificationFilter
  74. {
  75. nearest,
  76. linear
  77. };
  78. /** Sets the texture magnification filter. By default the texture magnification
  79. filter is linear. However, for faster rendering you may want to use the
  80. 'nearest' magnification filter. This option will not affect any textures
  81. created before this function was called. */
  82. void setTextureMagnificationFilter (TextureMagnificationFilter magFilterMode) noexcept;
  83. //==============================================================================
  84. /** Provides a context with which you'd like this context's resources to be shared.
  85. The object passed-in here is a platform-dependent native context object, and
  86. must not be deleted while this context may still be using it! To turn off sharing,
  87. you can call this method with a null pointer.
  88. Note: This must be called BEFORE attaching your context to a target component!
  89. */
  90. void setNativeSharedContext (void* nativeContextToShareWith) noexcept;
  91. /** Enables multisampling on platforms where this is implemented.
  92. If enabling this, you must call this method before attachTo().
  93. */
  94. void setMultisamplingEnabled (bool) noexcept;
  95. /** Returns true if shaders can be used in this context. */
  96. bool areShadersAvailable() const;
  97. /** OpenGL versions, used by setOpenGLVersionRequired(). */
  98. enum OpenGLVersion
  99. {
  100. defaultGLVersion = 0,
  101. openGL3_2
  102. };
  103. /** Sets a preference for the version of GL that this context should use, if possible.
  104. Some platforms may ignore this value.
  105. */
  106. void setOpenGLVersionRequired (OpenGLVersion) noexcept;
  107. /** Enables or disables the use of the GL context to perform 2D rendering
  108. of the component to which it is attached.
  109. If this is false, then only your OpenGLRenderer will be used to perform
  110. any rendering. If true, then each time your target's paint() method needs
  111. to be called, an OpenGLGraphicsContext will be used to render it, (after
  112. calling your OpenGLRenderer if there is one).
  113. By default this is set to true. If you're not using any paint() method functionality
  114. and are doing all your rendering in an OpenGLRenderer, you should disable it
  115. to improve performance.
  116. Note: This must be called BEFORE attaching your context to a target component!
  117. */
  118. void setComponentPaintingEnabled (bool shouldPaintComponent) noexcept;
  119. /** Enables or disables continuous repainting.
  120. If set to true, the context will run a loop, re-rendering itself without waiting
  121. for triggerRepaint() to be called, at a frequency determined by the swap interval
  122. (see setSwapInterval). If false, then after each render callback, it will wait for
  123. another call to triggerRepaint() before rendering again.
  124. This is disabled by default.
  125. @see setSwapInterval
  126. */
  127. void setContinuousRepainting (bool shouldContinuouslyRepaint) noexcept;
  128. /** Asynchronously causes a repaint to be made. */
  129. void triggerRepaint();
  130. //==============================================================================
  131. /** This retrieves an object that was previously stored with setAssociatedObject().
  132. If no object is found with the given name, this will return nullptr.
  133. This method must only be called from within the GL rendering methods.
  134. @see setAssociatedObject
  135. */
  136. ReferenceCountedObject* getAssociatedObject (const char* name) const;
  137. /** Attaches a named object to the context, which will be deleted when the context is
  138. destroyed.
  139. This allows you to store an object which will be released before the context is
  140. deleted. The main purpose is for caching GL objects such as shader programs, which
  141. will become invalid when the context is deleted.
  142. This method must only be called from within the GL rendering methods.
  143. */
  144. void setAssociatedObject (const char* name, ReferenceCountedObject* newObject);
  145. //==============================================================================
  146. /** Makes this context the currently active one.
  147. You should never need to call this in normal use - the context will already be
  148. active when OpenGLRenderer::renderOpenGL() is invoked.
  149. */
  150. bool makeActive() const noexcept;
  151. /** Returns true if this context is currently active for the calling thread. */
  152. bool isActive() const noexcept;
  153. /** If any context is active on the current thread, this deactivates it.
  154. Note that on some platforms, like Android, this isn't possible.
  155. */
  156. static void deactivateCurrentContext();
  157. /** Returns the context that's currently in active use by the calling thread, or
  158. nullptr if no context is active.
  159. */
  160. static OpenGLContext* getCurrentContext();
  161. //==============================================================================
  162. /** Swaps the buffers (if the context can do this).
  163. There's normally no need to call this directly - the buffers will be swapped
  164. automatically after your OpenGLRenderer::renderOpenGL() method has been called.
  165. */
  166. void swapBuffers();
  167. /** Sets whether the context checks the vertical sync before swapping.
  168. The value is the number of frames to allow between buffer-swapping. This is
  169. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  170. and greater numbers indicate that it should swap less often.
  171. By default, this will be set to 1.
  172. Returns true if it sets the value successfully - some platforms won't support
  173. this setting.
  174. @see setContinuousRepainting
  175. */
  176. bool setSwapInterval (int numFramesPerSwap);
  177. /** Returns the current swap-sync interval.
  178. See setSwapInterval() for info about the value returned.
  179. */
  180. int getSwapInterval() const;
  181. //==============================================================================
  182. /** Execute a lambda, function or functor on the OpenGL thread with an active
  183. context.
  184. This method will attempt to execute functor on the OpenGL thread. If
  185. blockUntilFinished is true then the method will block until the functor
  186. has finished executing.
  187. This function can only be called if the context is attached to a component.
  188. Otherwise, this function will assert.
  189. This function is useful when you need to execute house-keeping tasks such
  190. as allocating, deallocating textures or framebuffers. As such, the functor
  191. will execute without locking the message thread. Therefore, it is not
  192. intended for any drawing commands or GUI code. Any GUI code should be
  193. executed in the OpenGLRenderer::renderOpenGL callback instead.
  194. */
  195. template <typename T>
  196. void executeOnGLThread (T&& functor, bool blockUntilFinished);
  197. //==============================================================================
  198. /** Returns the scale factor used by the display that is being rendered.
  199. The scale is that of the display - see Displays::Display::scale
  200. Note that this should only be called during an OpenGLRenderer::renderOpenGL()
  201. callback - at other times the value it returns is undefined.
  202. */
  203. double getRenderingScale() const noexcept { return currentRenderScale; }
  204. //==============================================================================
  205. /** If this context is backed by a frame buffer, this returns its ID number,
  206. or 0 if the context does not use a framebuffer.
  207. */
  208. unsigned int getFrameBufferID() const noexcept;
  209. /** Returns an OS-dependent handle to some kind of underlying OS-provided GL context.
  210. The exact type of the value returned will depend on the OS and may change
  211. if the implementation changes. If you want to use this, digging around in the
  212. native code is probably the best way to find out what it is.
  213. */
  214. void* getRawContext() const noexcept;
  215. /** This structure holds a set of dynamically loaded GL functions for use on this context. */
  216. OpenGLExtensionFunctions extensions;
  217. //==============================================================================
  218. /** Draws the currently selected texture into this context at its original size.
  219. @param targetClipArea the target area to draw into (in top-left origin coords)
  220. @param anchorPosAndTextureSize the position of this rectangle is the texture's top-left
  221. anchor position in the target space, and the size must be
  222. the total size of the texture.
  223. @param contextWidth the width of the context or framebuffer that is being drawn into,
  224. used for scaling of the coordinates.
  225. @param contextHeight the height of the context or framebuffer that is being drawn into,
  226. used for vertical flipping of the y coordinates.
  227. @param textureOriginIsBottomLeft if true, the texture's origin is treated as being at
  228. (0, 0). If false, it is assumed to be (0, 1)
  229. */
  230. void copyTexture (const Rectangle<int>& targetClipArea,
  231. const Rectangle<int>& anchorPosAndTextureSize,
  232. int contextWidth, int contextHeight,
  233. bool textureOriginIsBottomLeft);
  234. /** Changes the amount of GPU memory that the internal cache for Images is allowed to use. */
  235. void setImageCacheSize (size_t cacheSizeBytes) noexcept;
  236. /** Returns the amount of GPU memory that the internal cache for Images is allowed to use. */
  237. size_t getImageCacheSize() const noexcept;
  238. //==============================================================================
  239. #ifndef DOXYGEN
  240. class NativeContext;
  241. #endif
  242. private:
  243. friend class OpenGLTexture;
  244. class CachedImage;
  245. class Attachment;
  246. NativeContext* nativeContext = nullptr;
  247. OpenGLRenderer* renderer = nullptr;
  248. double currentRenderScale = 1.0;
  249. std::unique_ptr<Attachment> attachment;
  250. OpenGLPixelFormat openGLPixelFormat;
  251. void* contextToShareWith = nullptr;
  252. OpenGLVersion versionRequired = defaultGLVersion;
  253. size_t imageCacheMaxSize = 8 * 1024 * 1024;
  254. bool renderComponents = true, useMultisampling = false, continuousRepaint = false, overrideCanAttach = false;
  255. TextureMagnificationFilter texMagFilter = linear;
  256. //==============================================================================
  257. struct AsyncWorker : public ReferenceCountedObject
  258. {
  259. using Ptr = ReferenceCountedObjectPtr<AsyncWorker>;
  260. virtual void operator() (OpenGLContext&) = 0;
  261. ~AsyncWorker() override = default;
  262. };
  263. template <typename FunctionType>
  264. struct AsyncWorkerFunctor : public AsyncWorker
  265. {
  266. AsyncWorkerFunctor (FunctionType functorToUse) : functor (functorToUse) {}
  267. void operator() (OpenGLContext& callerContext) override { functor (callerContext); }
  268. FunctionType functor;
  269. JUCE_DECLARE_NON_COPYABLE (AsyncWorkerFunctor)
  270. };
  271. //==============================================================================
  272. CachedImage* getCachedImage() const noexcept;
  273. void execute (AsyncWorker::Ptr, bool);
  274. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext)
  275. };
  276. //==============================================================================
  277. #ifndef DOXYGEN
  278. template <typename FunctionType>
  279. void OpenGLContext::executeOnGLThread (FunctionType&& f, bool shouldBlock) { execute (new AsyncWorkerFunctor<FunctionType> (f), shouldBlock); }
  280. #endif
  281. } // namespace juce