BsGLRenderAPI.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsGLPrerequisites.h"
  5. #include "RenderAPI/BsRenderAPI.h"
  6. #include "BsGLHardwareBufferManager.h"
  7. #include "GLSL/BsGLSLProgramFactory.h"
  8. #include "Math/BsMatrix4.h"
  9. namespace bs { namespace ct
  10. {
  11. /** @addtogroup GL
  12. * @{
  13. */
  14. /** Implementation of a render system using OpenGL. Provides abstracted access to various low level OpenGL methods. */
  15. class GLRenderAPI : public RenderAPI
  16. {
  17. public:
  18. GLRenderAPI();
  19. ~GLRenderAPI();
  20. /** @copydoc RenderAPI::getName() */
  21. const StringID& getName() const override;
  22. /** @copydoc RenderAPI::setGraphicsPipeline */
  23. void setGraphicsPipeline(const SPtr<GraphicsPipelineState>& pipelineState,
  24. const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  25. /** @copydoc RenderAPI::setComputePipeline */
  26. void setComputePipeline(const SPtr<ComputePipelineState>& pipelineState,
  27. const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  28. /** @copydoc RenderAPI::setGpuParams() */
  29. void setGpuParams(const SPtr<GpuParams>& gpuParams,
  30. const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  31. /** @copydoc RenderAPI::setViewport() */
  32. void setViewport(const Rect2& area, const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  33. /** @copydoc RenderAPI::setScissorRect() */
  34. void setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom,
  35. const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  36. /** @copydoc RenderAPI::setStencilRef */
  37. void setStencilRef(UINT32 value, const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  38. /** @copydoc RenderAPI::setVertexBuffers() */
  39. void setVertexBuffers(UINT32 index, SPtr<VertexBuffer>* buffers, UINT32 numBuffers,
  40. const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  41. /** @copydoc RenderAPI::setIndexBuffer() */
  42. void setIndexBuffer(const SPtr<IndexBuffer>& buffer,
  43. const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  44. /** @copydoc RenderAPI::setVertexDeclaration() */
  45. void setVertexDeclaration(const SPtr<VertexDeclaration>& vertexDeclaration,
  46. const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  47. /** @copydoc RenderAPI::setDrawOperation() */
  48. void setDrawOperation(DrawOperationType op, const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  49. /** @copydoc RenderAPI::draw() */
  50. void draw(UINT32 vertexOffset, UINT32 vertexCount, UINT32 instanceCount = 0,
  51. const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  52. /** @copydoc RenderAPI::drawIndexed() */
  53. void drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount
  54. , UINT32 instanceCount = 0, const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  55. /** @copydoc RenderAPI::dispatchCompute() */
  56. void dispatchCompute(UINT32 numGroupsX, UINT32 numGroupsY = 1, UINT32 numGroupsZ = 1,
  57. const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  58. /** @copydoc RenderAPI::swapBuffers() */
  59. void swapBuffers(const SPtr<RenderTarget>& target, UINT32 syncMask = 0xFFFFFFFF) override;
  60. /** @copydoc RenderAPI::setRenderTarget() */
  61. void setRenderTarget(const SPtr<RenderTarget>& target, UINT32 readOnlyFlags = 0,
  62. RenderSurfaceMask loadMask = RT_NONE, const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  63. /** @copydoc RenderAPI::clearRenderTarget() */
  64. void clearRenderTarget(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0,
  65. UINT8 targetMask = 0xFF, const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  66. /** @copydoc RenderAPI::clearViewport() */
  67. void clearViewport(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0,
  68. UINT8 targetMask = 0xFF, const SPtr<CommandBuffer>& commandBuffer = nullptr) override;
  69. /** @copydoc RenderAPI::addCommands() */
  70. void addCommands(const SPtr<CommandBuffer>& commandBuffer, const SPtr<CommandBuffer>& secondary) override;
  71. /** @copydoc RenderAPI::submitCommandBuffer() */
  72. void submitCommandBuffer(const SPtr<CommandBuffer>& commandBuffer, UINT32 syncMask = 0xFFFFFFFF) override;
  73. /** @copydoc RenderAPI::convertProjectionMatrix() */
  74. void convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest) override;
  75. /** @copydoc RenderAPI::getAPIInfo */
  76. const RenderAPIInfo& getAPIInfo() const override;
  77. /** @copydoc RenderAPI::generateParamBlockDesc() */
  78. GpuParamBlockDesc generateParamBlockDesc(const String& name, Vector<GpuParamDataDesc>& params) override;
  79. /************************************************************************/
  80. /* Internal use by OpenGL RenderSystem only */
  81. /************************************************************************/
  82. /** Query has the main context been initialized. */
  83. bool _isContextInitialized() const { return mGLInitialised; }
  84. /** Returns main context. Caller must ensure the context has been initialized. */
  85. SPtr<GLContext> _getMainContext() const { return mMainContext; }
  86. /** Returns a support object you may use for creating */
  87. GLSupport* getGLSupport() const { return mGLSupport; }
  88. protected:
  89. /** @copydoc RenderAPI::initialize */
  90. void initialize() override;
  91. /** @copydoc RenderAPI::initializeWithWindow */
  92. void initializeWithWindow(const SPtr<RenderWindow>& primaryWindow) override;
  93. /** @copydoc RenderAPI::destroyCore */
  94. void destroyCore() override;
  95. /** Call before doing a draw operation, this method sets everything up. */
  96. void beginDraw();
  97. /** Needs to accompany every beginDraw after you are done with a single draw operation. */
  98. void endDraw();
  99. /** Clear a part of a render target. */
  100. void clearArea(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0,
  101. const Rect2I& clearArea = Rect2I::EMPTY, UINT8 targetMask = 0xFF);
  102. /**
  103. * Changes the currently active texture unit. Any texture related operations will then be performed on this unit.
  104. */
  105. bool activateGLTextureUnit(UINT16 unit);
  106. /** Retrieves the active GPU program of the specified type. */
  107. SPtr<GLSLGpuProgram> getActiveProgram(GpuProgramType gptype) const;
  108. /** Converts Banshee blend mode to OpenGL blend mode. */
  109. GLint getBlendMode(BlendFactor blendMode) const;
  110. /** Converts Banshee texture addressing mode to OpenGL texture addressing mode. */
  111. GLint getTextureAddressingMode(TextureAddressingMode tam) const;
  112. /** Gets a combined min/mip filter value usable by OpenGL from the currently set min and mip filters. */
  113. GLuint getCombinedMinMipFilter() const;
  114. /** Returns the OpenGL specific mode used for drawing, depending on the currently set draw operation. */
  115. GLint getGLDrawMode() const;
  116. /** Creates render system capabilities that specify which features are or aren't supported. */
  117. void initCapabilities(RenderAPICapabilities& caps) const;
  118. /** Finish initialization by setting up any systems dependant on render systemcapabilities. */
  119. void initFromCaps(RenderAPICapabilities* caps);
  120. /**
  121. * Switch the currently used OpenGL context. You will need to re-bind any previously bound values manually
  122. * (for example textures, gpu programs and such).
  123. */
  124. void switchContext(const SPtr<GLContext>& context, const RenderWindow& window);
  125. /************************************************************************/
  126. /* Sampler states */
  127. /************************************************************************/
  128. /**
  129. * Sets the texture addressing mode for a texture unit. This determines how are UV address values outside of [0, 1]
  130. * range handled when sampling from texture.
  131. */
  132. void setTextureAddressingMode(UINT16 unit, const UVWAddressingMode& uvw);
  133. /**
  134. * Sets the texture border color for a texture unit. Border color determines color returned by the texture sampler
  135. * when border addressing mode is used and texture address is outside of [0, 1] range.
  136. */
  137. void setTextureBorderColor(UINT16 unit, const Color& color);
  138. /**
  139. * Sets the mipmap bias value for a given texture unit. Bias allows you to adjust the mipmap selection calculation.
  140. * Negative values force a larger mipmap to be used, and positive values smaller. Units are in values of mip levels,
  141. * so -1 means use a mipmap one level higher than default.
  142. */
  143. void setTextureMipmapBias(UINT16 unit, float bias);
  144. /**
  145. * Sets a valid range for mipmaps (LOD) for a given texture unit. @p min limits the selection of the highest
  146. * resolution mipmap (lowest level), and @p max limits the selection of the lowest resolution mipmap (highest
  147. * level).
  148. */
  149. void setTextureMipmapRange(UINT16 unit, float min, float max);
  150. /**
  151. * Allows you to specify how is the texture bound to the specified texture unit filtered. Different filter types are
  152. * used for different situations like magnifying or minifying a texture.
  153. */
  154. void setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions filter);
  155. /** Sets anisotropy value for the specified texture unit. */
  156. void setTextureAnisotropy(UINT16 unit, UINT32 maxAnisotropy);
  157. /**
  158. * Sets the compare mode to use when sampling the texture (anything but "always" implies the use of a shadow
  159. * sampler.
  160. */
  161. void setTextureCompareMode(UINT16 unit, CompareFunction compare);
  162. /** Gets anisotropy value for the specified texture unit. */
  163. GLfloat getCurrentAnisotropy(UINT16 unit);
  164. /************************************************************************/
  165. /* Blend states */
  166. /************************************************************************/
  167. /**
  168. * Sets up blending mode that allows you to combine new pixels with pixels already in the render target.
  169. * Final pixel value = (renderTargetPixel * sourceFactor) op (pixel * destFactor).
  170. */
  171. void setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op);
  172. /**
  173. * Sets up blending mode that allows you to combine new pixels with pixels already in the render target.
  174. * Allows you to set up separate blend operations for alpha values.
  175. *
  176. * Final pixel value = (renderTargetPixel * sourceFactor) op (pixel * destFactor). (And the same for alpha)
  177. */
  178. void setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendFactor sourceFactorAlpha,
  179. BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp);
  180. /**
  181. * Enable alpha to coverage. Alpha to coverage allows you to perform blending without needing to worry about order
  182. * of rendering like regular blending does. It requires multi-sampling to be active in order to work, and you need
  183. * to supply an alpha texture that determines object transparency.
  184. */
  185. void setAlphaToCoverage(bool enabled);
  186. /** Enables or disables writing to certain color channels of the render target. */
  187. void setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha);
  188. /************************************************************************/
  189. /* Rasterizer states */
  190. /************************************************************************/
  191. /** Sets vertex winding order. Normally you would use this to cull back facing polygons. */
  192. void setCullingMode(CullingMode mode);
  193. /** Sets the polygon rasterization mode. Determines how are polygons interpreted. */
  194. void setPolygonMode(PolygonMode level);
  195. /**
  196. * Sets a depth bias that will offset the depth values of new pixels by the specified amount. Final depth bias value
  197. * is a combination of the constant depth bias and slope depth bias. Slope depth bias has more effect the higher
  198. * the slope of the rendered polygon.
  199. *
  200. * @note This is useful if you want to avoid z fighting for objects at the same or similar depth.
  201. */
  202. void setDepthBias(float constantBias, float slopeScaleBias);
  203. /**
  204. * Scissor test allows you to mask off rendering in all but a given rectangular area identified by the rectangle
  205. * set by setScissorRect().
  206. */
  207. void setScissorTestEnable(bool enable);
  208. /** Enables or disables multisample antialiasing. */
  209. void setMultisamplingEnable(bool enable);
  210. /** Enables or disables depth clipping (near/fear plane clipping). */
  211. void setDepthClipEnable(bool enable);
  212. /** Enables or disables antialiased line rendering. */
  213. void setAntialiasedLineEnable(bool enable);
  214. /************************************************************************/
  215. /* Depth stencil state */
  216. /************************************************************************/
  217. /** Should new pixels perform depth testing using the set depth comparison function before being written. */
  218. void setDepthBufferCheckEnabled(bool enabled = true);
  219. /** Should new pixels write to the depth buffer. */
  220. void setDepthBufferWriteEnabled(bool enabled = true);
  221. /**
  222. * Sets comparison function used for depth testing. Determines how are new and existing pixel values compared - if
  223. * comparison function returns true the new pixel is written.
  224. */
  225. void setDepthBufferFunction(CompareFunction func = CMPF_LESS_EQUAL);
  226. /**
  227. * Turns stencil tests on or off. By default this is disabled. Stencil testing allow you to mask out a part of the
  228. * rendered image by using various stencil operations provided.
  229. */
  230. void setStencilCheckEnabled(bool enabled);
  231. /**
  232. * Allows you to set stencil operations that are performed when stencil test passes or fails.
  233. *
  234. * @param[in] stencilFailOp Operation executed when stencil test fails.
  235. * @param[in] depthFailOp Operation executed when stencil test succeeds but depth test fails.
  236. * @param[in] passOp Operation executed when stencil test succeeds and depth test succeeds.
  237. * @param[in] front Should the stencil operations be applied to front or back facing polygons.
  238. */
  239. void setStencilBufferOperations(StencilOperation stencilFailOp = SOP_KEEP,
  240. StencilOperation depthFailOp = SOP_KEEP, StencilOperation passOp = SOP_KEEP,
  241. bool front = true);
  242. /**
  243. * Sets a stencil buffer comparison function. The result of this will cause one of 3 actions depending on whether
  244. * the test fails, succeeds but with the depth buffer check still failing, or succeeds with the depth buffer check
  245. * passing too.
  246. *
  247. * @param[in] func Comparison function that determines whether a stencil test fails or passes. Reference value
  248. * gets compared to the value already in the buffer using this function.
  249. * @param[in] mask The bitmask applied to both the stencil value and the reference value
  250. * before comparison
  251. * @param[in] ccw If set to true, the stencil operations will be applied to counterclockwise
  252. * faces. Otherwise they will be applied to clockwise faces.
  253. */
  254. void setStencilBufferFunc(CompareFunction func = CMPF_ALWAYS_PASS, UINT32 mask = 0xFFFFFFFF, bool ccw = true);
  255. /** The bitmask applied to the stencil value before writing it to the stencil buffer. */
  256. void setStencilBufferWriteMask(UINT32 mask = 0xFFFFFFFF);
  257. /**
  258. * Sets a reference values used for stencil buffer comparisons. Actual comparison function and stencil operations
  259. * are set by setting the DepthStencilState.
  260. */
  261. void setStencilRefValue(UINT32 refValue);
  262. /************************************************************************/
  263. /* UTILITY METHODS */
  264. /************************************************************************/
  265. /**
  266. * Recalculates actual viewport dimensions based on currently set viewport normalized dimensions and render target
  267. * and applies them for further rendering.
  268. */
  269. void applyViewport();
  270. /** Converts the provided matrix m into a representation usable by OpenGL. */
  271. void makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m);
  272. /** Converts the engine depth/stencil compare function into OpenGL representation. */
  273. GLint convertCompareFunction(CompareFunction func) const;
  274. /** Convers the engine stencil operation in OpenGL representation. */
  275. GLint convertStencilOp(StencilOperation op) const;
  276. private:
  277. /** Information about a currently bound texture. */
  278. struct TextureInfo
  279. {
  280. GLenum type;
  281. };
  282. static const UINT32 MAX_VB_COUNT = 32;
  283. Rect2 mViewportNorm;
  284. UINT32 mScissorTop, mScissorBottom, mScissorLeft, mScissorRight;
  285. UINT32 mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight;
  286. bool mScissorEnabled;
  287. UINT32 mStencilReadMask;
  288. UINT32 mStencilWriteMask;
  289. UINT32 mStencilRefValue;
  290. CompareFunction mStencilCompareFront;
  291. CompareFunction mStencilCompareBack;
  292. // Last min & mip filtering options, so we can combine them
  293. FilterOptions mMinFilter;
  294. FilterOptions mMipFilter;
  295. // Holds texture type settings for every stage
  296. UINT32 mNumTextureUnits;
  297. TextureInfo* mTextureInfos;
  298. bool mDepthWrite;
  299. bool mColorWrite[4];
  300. GLSupport* mGLSupport;
  301. bool mGLInitialised;
  302. GLSLProgramFactory* mGLSLProgramFactory;
  303. GLSLProgramPipelineManager* mProgramPipelineManager;
  304. SPtr<GLSLGpuProgram> mCurrentVertexProgram;
  305. SPtr<GLSLGpuProgram> mCurrentFragmentProgram;
  306. SPtr<GLSLGpuProgram> mCurrentGeometryProgram;
  307. SPtr<GLSLGpuProgram> mCurrentHullProgram;
  308. SPtr<GLSLGpuProgram> mCurrentDomainProgram;
  309. SPtr<GLSLGpuProgram> mCurrentComputeProgram;
  310. const GLSLProgramPipeline* mActivePipeline;
  311. std::array<SPtr<VertexBuffer>, MAX_VB_COUNT> mBoundVertexBuffers;
  312. SPtr<VertexDeclaration> mBoundVertexDeclaration;
  313. SPtr<IndexBuffer> mBoundIndexBuffer;
  314. DrawOperationType mCurrentDrawOperation;
  315. SPtr<GLContext> mMainContext;
  316. SPtr<GLContext> mCurrentContext;
  317. bool mDrawCallInProgress;
  318. UINT16 mActiveTextureUnit;
  319. };
  320. /** @} */
  321. }}