CCGLProgramState.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /****************************************************************************
  2. Copyright (c) 2014-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. Autobinding Interface from GamePlay3D: http://www.gameplay3d.org/
  21. ****************************************************************************/
  22. #ifndef __CCGLPROGRAMSTATE_H__
  23. #define __CCGLPROGRAMSTATE_H__
  24. #include <unordered_map>
  25. #include "base/ccTypes.h"
  26. #include "base/CCVector.h"
  27. #include "math/Vec2.h"
  28. #include "math/Vec3.h"
  29. #include "math/Vec4.h"
  30. /**
  31. * @addtogroup renderer
  32. * @{
  33. */
  34. NS_CC_BEGIN
  35. class GLProgram;
  36. class Texture2D;
  37. struct Uniform;
  38. struct VertexAttrib;
  39. class EventListenerCustom;
  40. class EventCustom;
  41. class Node;
  42. /**
  43. * Uniform Value, which is used to store to value send to openGL pipe line by glUniformXXX.
  44. *
  45. * @lua NA
  46. */
  47. class CC_DLL UniformValue
  48. {
  49. friend class GLProgram;
  50. friend class GLProgramState;
  51. public:
  52. /**
  53. Constructor. The Uniform and Glprogram will be nullptr.
  54. */
  55. UniformValue();
  56. /**
  57. Constructor with uniform and glprogram.
  58. @param uniform Uniform to apply the value.
  59. @param glprogram Specify the owner GLProgram of this uniform and uniform value.
  60. */
  61. UniformValue(Uniform *uniform, GLProgram* glprogram);
  62. UniformValue(const UniformValue& o);
  63. /**Destructor.*/
  64. ~UniformValue();
  65. /**@{
  66. Set data to Uniform value. Generally, there are many type of data could be supported,
  67. including float, int, Vec2/3/4, Mat4.
  68. @param value Value to be sent, support float, int, Vec2/3/4, Mat4.
  69. */
  70. void setFloat(float value);
  71. void setInt(int value);
  72. void setFloatv(ssize_t size, const float* pointer);
  73. void setVec2(const Vec2& value);
  74. void setVec2v(ssize_t size, const Vec2* pointer);
  75. void setVec3(const Vec3& value);
  76. void setVec3v(ssize_t size, const Vec3* pointer);
  77. void setVec4(const Vec4& value);
  78. void setVec4v(ssize_t size, const Vec4* pointer);
  79. void setMat4(const Mat4& value);
  80. /**
  81. @}
  82. */
  83. /**
  84. Set call back to uniform value, which could be used for array and struct.
  85. @param callback Callback function to send data to OpenGL pipeline.
  86. */
  87. void setCallback(const std::function<void(GLProgram*, Uniform*)> &callback);
  88. /**
  89. Set texture to uniform value.
  90. @param textureId The texture handle.
  91. @param textureUnit The binding texture unit to be used in shader.
  92. @deprecated please use setTexture(Texture2D* texture, GLuint textureUnit) instead,
  93. Passing a `textureId` may trigger texture lost issue (https://github.com/cocos2d/cocos2d-x/issues/16871).
  94. */
  95. CC_DEPRECATED_ATTRIBUTE void setTexture(GLuint textureId, GLuint textureUnit);
  96. /**
  97. Set texture to uniform value.
  98. @param texture The texture.
  99. @param textureUnit The binding texture unit to be used in shader.
  100. */
  101. void setTexture(Texture2D* texture, GLuint textureUnit);
  102. /**Apply the uniform value to openGL pipeline.*/
  103. void apply();
  104. UniformValue& operator=(const UniformValue& o);
  105. protected:
  106. enum class Type {
  107. VALUE,
  108. POINTER,
  109. CALLBACK_FN // CALLBACK is already defined in windows, can't use it.
  110. };
  111. /**Weak reference to Uniform.*/
  112. Uniform* _uniform;
  113. /**Weak reference to GLprogram.*/
  114. GLProgram* _glprogram;
  115. /** What kind of type is the Uniform */
  116. Type _type;
  117. /**
  118. @name Uniform Value Uniform
  119. @{
  120. */
  121. union U{
  122. float floatValue;
  123. int intValue;
  124. float v2Value[2];
  125. float v3Value[3];
  126. float v4Value[4];
  127. float matrixValue[16];
  128. struct {
  129. GLuint textureId; // textureId will be deprecated since we use 'texture->getName()' to get textureId.
  130. GLuint textureUnit;
  131. Texture2D* texture;
  132. } tex;
  133. struct {
  134. const float* pointer;
  135. GLsizei size;
  136. } floatv;
  137. struct {
  138. const float* pointer;
  139. GLsizei size;
  140. } v2f;
  141. struct {
  142. const float* pointer;
  143. GLsizei size;
  144. } v3f;
  145. struct {
  146. const float* pointer;
  147. GLsizei size;
  148. } v4f;
  149. std::function<void(GLProgram*, Uniform*)> *callback;
  150. U() { memset( this, 0, sizeof(*this) ); }
  151. ~U(){}
  152. U& operator=( const U& other ) {
  153. memcpy(this, &other, sizeof(*this));
  154. return *this;
  155. }
  156. } _value;
  157. /**
  158. @}
  159. */
  160. };
  161. /**
  162. * Vertex Attribute Value, which is an abstraction of VertexAttribute and data pointer.
  163. *
  164. * @lua NA
  165. */
  166. class CC_DLL VertexAttribValue
  167. {
  168. friend class GLProgram;
  169. friend class GLProgramState;
  170. friend class VertexAttribBinding;
  171. public:
  172. /**
  173. Constructor.
  174. @param vertexAttrib VertexAttrib from shader.
  175. */
  176. VertexAttribValue(VertexAttrib *vertexAttrib);
  177. /**
  178. Constructor.
  179. */
  180. VertexAttribValue();
  181. /**
  182. Destructor.
  183. */
  184. ~VertexAttribValue();
  185. /**
  186. Set the data pointer, which is similar as glVertexAttribPointer.
  187. @param size The number of type in the vertex attribute.
  188. @param type The type of data in vertex attribute.
  189. @param normalized If true, 0-255 data will be mapped to 0.0-1.0.
  190. @param stride The number of bytes if an interleaved vertex array is used. 0 means array is not interleaved.
  191. @param pointer The pointer to the vertex data.
  192. */
  193. void setPointer(GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLvoid *pointer);
  194. /**Set a user call back for set VertexAttrib array.*/
  195. void setCallback(const std::function<void(VertexAttrib*)> &callback);
  196. /**Apply the vertex attribute to the openGL pipeline.*/
  197. void apply();
  198. protected:
  199. VertexAttrib* _vertexAttrib; // weak ref
  200. bool _useCallback;
  201. bool _enabled;
  202. union U{
  203. struct {
  204. GLint size;
  205. GLenum type;
  206. GLboolean normalized;
  207. GLsizei stride;
  208. GLvoid *pointer;
  209. } pointer;
  210. std::function<void(VertexAttrib*)> *callback;
  211. U() { memset( this, 0, sizeof(*this) ); }
  212. ~U(){}
  213. U& operator=( const U& other ) {
  214. memcpy(this, &other, sizeof(*this));
  215. return *this;
  216. }
  217. } _value;
  218. };
  219. /**
  220. GLProgramState holds the 'state' (uniforms and attributes) of the GLProgram.
  221. A GLProgram can be used by thousands of Nodes, but if different uniform values
  222. are going to be used, then each node will need its own GLProgramState
  223. */
  224. class CC_DLL GLProgramState : public Ref
  225. {
  226. friend class GLProgramStateCache;
  227. public:
  228. /** returns a new instance of GLProgramState for a given GLProgram */
  229. static GLProgramState* create(GLProgram* glprogram);
  230. /** gets-or-creates an instance of GLProgramState for a given GLProgram */
  231. static GLProgramState* getOrCreateWithGLProgram(GLProgram* glprogram);
  232. /** gets-or-creates an instance of GLProgramState for a given GLProgramName */
  233. static GLProgramState* getOrCreateWithGLProgramName(const std::string& glProgramName );
  234. /** gets-or-creates an instance of GLProgramState for the given GLProgramName & texture */
  235. static GLProgramState* getOrCreateWithGLProgramName(const std::string& glProgramName, Texture2D* texture);
  236. /** gets-or-creates an instance of GLProgramState for given shaders */
  237. static GLProgramState* getOrCreateWithShaders(const std::string& vertexShader, const std::string& fragShader, const std::string& compileTimeDefines);
  238. /** Returns a new copy of the GLProgramState. The GLProgram is reused */
  239. GLProgramState* clone() const;
  240. /**
  241. Apply GLProgram, attributes and uniforms.
  242. @param modelView The applied modelView matrix to shader.
  243. */
  244. void apply(const Mat4& modelView);
  245. /**
  246. Apply GLProgram, and built in uniforms.
  247. @param modelView The applied modelView matrix to shader.
  248. */
  249. void applyGLProgram(const Mat4& modelView);
  250. /**
  251. Apply attributes.
  252. @param applyAttribFlags Call GL::enableVertexAttribs(_vertexAttribsFlags) or not.
  253. */
  254. void applyAttributes(bool applyAttribFlags = true);
  255. /**
  256. Apply user defined uniforms.
  257. */
  258. void applyUniforms();
  259. /**@{
  260. Setter and Getter of the owner GLProgram binded in this program state.
  261. */
  262. void setGLProgram(GLProgram* glprogram);
  263. GLProgram* getGLProgram() const { return _glprogram; }
  264. /**@}*/
  265. /** Get the flag of vertex attribs used by OR operation.*/
  266. uint32_t getVertexAttribsFlags() const;
  267. /**Get the number of vertex attributes.*/
  268. ssize_t getVertexAttribCount() const;
  269. /**@{
  270. Set the vertex attribute value.
  271. */
  272. void setVertexAttribCallback(const std::string& name, const std::function<void(VertexAttrib*)> &callback);
  273. void setVertexAttribPointer(const std::string& name, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLvoid *pointer);
  274. /**@}*/
  275. /**Get the number of user defined uniform count.*/
  276. ssize_t getUniformCount() const { return _uniforms.size(); }
  277. /** @{
  278. Setting user defined uniforms by uniform string name in the shader.
  279. */
  280. void setUniformInt(const std::string& uniformName, int value);
  281. void setUniformFloat(const std::string& uniformName, float value);
  282. void setUniformFloatv(const std::string& uniformName, ssize_t size, const float* pointer);
  283. void setUniformVec2(const std::string& uniformName, const Vec2& value);
  284. void setUniformVec2v(const std::string& uniformName, ssize_t size, const Vec2* pointer);
  285. void setUniformVec3(const std::string& uniformName, const Vec3& value);
  286. void setUniformVec3v(const std::string& uniformName, ssize_t size, const Vec3* pointer);
  287. void setUniformVec4(const std::string& uniformName, const Vec4& value);
  288. void setUniformVec4v(const std::string& uniformName, ssize_t size, const Vec4* pointer);
  289. void setUniformMat4(const std::string& uniformName, const Mat4& value);
  290. void setUniformCallback(const std::string& uniformName, const std::function<void(GLProgram*, Uniform*)> &callback);
  291. void setUniformTexture(const std::string& uniformName, Texture2D *texture);
  292. /**
  293. * @deprecated, please use setUniformTexture(const std::string& uniformName, Texture2D *texture) instead,
  294. * Passing a `textureId` may trigger texture lost issue (https://github.com/cocos2d/cocos2d-x/issues/16871).
  295. */
  296. CC_DEPRECATED_ATTRIBUTE void setUniformTexture(const std::string& uniformName, GLuint textureId);
  297. /**@}*/
  298. /** @{
  299. Setting user defined uniforms by uniform location in the shader.
  300. */
  301. void setUniformInt(GLint uniformLocation, int value);
  302. void setUniformFloat(GLint uniformLocation, float value);
  303. void setUniformFloatv(GLint uniformLocation, ssize_t size, const float* pointer);
  304. void setUniformVec2(GLint uniformLocation, const Vec2& value);
  305. void setUniformVec2v(GLint uniformLocation, ssize_t size, const Vec2* pointer);
  306. void setUniformVec3(GLint uniformLocation, const Vec3& value);
  307. void setUniformVec3v(GLint uniformLocation, ssize_t size, const Vec3* pointer);
  308. void setUniformVec4(GLint uniformLocation, const Vec4& value);
  309. void setUniformVec4v(GLint uniformLocation, ssize_t size, const Vec4* pointer);
  310. void setUniformMat4(GLint uniformLocation, const Mat4& value);
  311. void setUniformCallback(GLint uniformLocation, const std::function<void(GLProgram*, Uniform*)> &callback);
  312. void setUniformTexture(GLint uniformLocation, Texture2D *texture);
  313. /**
  314. * @deprecated, please use setUniformTexture(GLint uniformLocation, Texture2D *texture) instead,
  315. * Passing a `textureId` may trigger texture lost issue (https://github.com/cocos2d/cocos2d-x/issues/16871).
  316. */
  317. CC_DEPRECATED_ATTRIBUTE void setUniformTexture(GLint uniformLocation, GLuint textureId);
  318. /**@}*/
  319. /**
  320. * Returns the Node bound to the GLProgramState
  321. */
  322. Node* getNodeBinding() const;
  323. /**
  324. * Sets the node that this render state is bound to.
  325. *
  326. * The specified node is used to apply auto-bindings for the render state.
  327. * This is typically set to the node of the model that a material is
  328. * applied to.
  329. *
  330. * @param node The node to use for applying auto-bindings.
  331. */
  332. void setNodeBinding(Node* node);
  333. /**
  334. * Applies the specified custom auto-binding.
  335. *
  336. * @param uniformName Name of the shader uniform.
  337. * @param autoBinding Name of the auto binding.
  338. */
  339. void applyAutoBinding(const std::string& uniformName, const std::string& autoBinding);
  340. /**
  341. * Sets a uniform auto-binding.
  342. *
  343. * This method parses the passed in autoBinding string and attempts to convert it
  344. * to an enumeration value. If it matches to one of the predefined strings, it will create a
  345. * callback to get the correct value at runtime.
  346. *
  347. * @param uniformName The name of the material parameter to store an auto-binding for.
  348. * @param autoBinding A string matching one of the built-in AutoBinding enum constants.
  349. */
  350. void setParameterAutoBinding(const std::string& uniformName, const std::string& autoBinding);
  351. /**
  352. * An abstract base class that can be extended to support custom material auto bindings.
  353. *
  354. * Implementing a custom auto binding resolver allows the set of built-in parameter auto
  355. * bindings to be extended or overridden. Any parameter auto binding that is set on a
  356. * material will be forwarded to any custom auto binding resolvers, in the order in which
  357. * they are registered. If a registered resolver returns true (specifying that it handles
  358. * the specified autoBinding), no further code will be executed for that autoBinding.
  359. * This allows auto binding resolvers to not only implement new/custom binding strings,
  360. * but it also lets them override existing/built-in ones. For this reason, you should
  361. * ensure that you ONLY return true if you explicitly handle a custom auto binding; return
  362. * false otherwise.
  363. *
  364. * Note that the custom resolver is called only once for a GLProgramState object when its
  365. * node binding is initially set. This occurs when a material is initially bound to a
  366. * Node. The resolver is NOT called each frame or each time the GLProgramState is bound.
  367. *
  368. * If no registered resolvers explicitly handle an auto binding, the binding will attempt
  369. * to be resolved using the internal/built-in resolver, which is able to handle any
  370. * auto bindings found in the GLProgramState::AutoBinding enumeration.
  371. *
  372. * When an instance of a class that extends AutoBindingResolver is created, it is automatically
  373. * registered as a custom auto binding handler. Likewise, it is automatically unregistered
  374. * on destruction.
  375. *
  376. * @script{ignore}
  377. */
  378. class CC_DLL AutoBindingResolver
  379. {
  380. public:
  381. /**
  382. * Destructor.
  383. */
  384. virtual ~AutoBindingResolver();
  385. /**
  386. * Called when an unrecognized uniform variable is encountered
  387. * during material loading.
  388. *
  389. * Implementations of this method should do a string comparison on the passed
  390. * in name parameter and decide whether or not they should handle the
  391. * parameter. If the parameter is not handled, false should be returned so
  392. * that other auto binding resolvers get a chance to handle the parameter.
  393. * Otherwise, the parameter should be set or bound and true should be returned.
  394. *
  395. * @param glProgramState The glProgramState
  396. * @param node The node that the material is attached to.
  397. * @param uniformName Name of the uniform
  398. * @param autoBinding Name of the auto binding to be resolved.
  399. *
  400. * @return True if the auto binding is handled and the associated parameter is
  401. * bound, false otherwise.
  402. */
  403. virtual bool resolveAutoBinding(GLProgramState* glProgramState, Node* node, const std::string& uniformName, const std::string& autoBinding) = 0;
  404. protected:
  405. /**
  406. * Constructor.
  407. */
  408. AutoBindingResolver();
  409. };
  410. protected:
  411. GLProgramState();
  412. virtual ~GLProgramState();
  413. bool init(GLProgram* program);
  414. void resetGLProgram();
  415. void updateUniformsAndAttributes();
  416. VertexAttribValue* getVertexAttribValue(const std::string& attributeName);
  417. UniformValue* getUniformValue(const std::string& uniformName);
  418. UniformValue* getUniformValue(GLint uniformLocation);
  419. bool _uniformAttributeValueDirty;
  420. std::unordered_map<std::string, GLint> _uniformsByName;
  421. std::unordered_map<GLint, UniformValue> _uniforms;
  422. std::unordered_map<std::string, VertexAttribValue> _attributes;
  423. std::unordered_map<std::string, int> _boundTextureUnits;
  424. int _textureUnitIndex;
  425. uint32_t _vertexAttribsFlags;
  426. GLProgram* _glprogram;
  427. Node* _nodeBinding; // weak ref
  428. // contains uniform name and variable
  429. std::unordered_map<std::string, std::string> _autoBindings;
  430. // Map of custom auto binding resolvers.
  431. static std::vector<AutoBindingResolver*> _customAutoBindingResolvers;
  432. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  433. EventListenerCustom* _backToForegroundlistener;
  434. #endif
  435. };
  436. NS_CC_END
  437. /**
  438. end of support group
  439. @}
  440. */
  441. #endif /* __CCGLPROGRAMSTATE_H__ */