BsGLRenderAPI.h 18 KB

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