CCGLProgram.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. /****************************************************************************
  2. Copyright 2011 Jeff Lamarche
  3. Copyright 2012 Goffredo Marocchi
  4. Copyright 2012 Ricardo Quesada
  5. Copyright 2012 cocos2d-x.org
  6. Copyright (c) 2013-2017 Chukong Technologies Inc.
  7. http://www.cocos2d-x.org
  8. Permission is hereby granted, free of charge, to any person obtaining a copy
  9. of this software and associated documentation files (the "Software"), to deal
  10. in the Software without restriction, including without limitation the rights
  11. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. copies of the Software, and to permit persons to whom the Software is
  13. furnished to do so, subject to the following conditions:
  14. The above copyright notice and this permission notice shall be included in
  15. all copies or substantial portions of the Software.
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN false EVENT SHALL THE
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. THE SOFTWARE.
  23. ****************************************************************************/
  24. #include "renderer/CCGLProgram.h"
  25. #ifndef WIN32
  26. #include <alloca.h>
  27. #endif
  28. #include "base/CCDirector.h"
  29. #include "base/ccUTF8.h"
  30. #include "renderer/ccGLStateCache.h"
  31. #include "platform/CCFileUtils.h"
  32. // helper functions
  33. static void replaceDefines(const std::string& compileTimeDefines, std::string& out)
  34. {
  35. // Replace semicolons with '#define ... \n'
  36. if (!compileTimeDefines.empty())
  37. {
  38. // append ';' if the last char doesn't have one
  39. auto copyDefines = compileTimeDefines;
  40. if (copyDefines[copyDefines.length()-1] != ';')
  41. copyDefines.append(1, ';');
  42. std::string currentDefine;
  43. for (auto itChar: copyDefines)
  44. {
  45. if (itChar == ';')
  46. {
  47. if (!currentDefine.empty())
  48. {
  49. out.append("\n#define " + currentDefine);
  50. currentDefine.clear();
  51. }
  52. }
  53. else
  54. {
  55. currentDefine.append(1, itChar);
  56. }
  57. }
  58. out += "\n";
  59. }
  60. }
  61. NS_CC_BEGIN
  62. const char* GLProgram::SHADER_NAME_ETC1AS_POSITION_TEXTURE_COLOR = "#ShaderETC1ASPositionTextureColor";
  63. const char* GLProgram::SHADER_NAME_ETC1AS_POSITION_TEXTURE_COLOR_NO_MVP = "#ShaderETC1ASPositionTextureColor_noMVP";
  64. const char* GLProgram::SHADER_NAME_ETC1AS_POSITION_TEXTURE_GRAY = "#ShaderETC1ASPositionTextureGray";
  65. const char* GLProgram::SHADER_NAME_ETC1AS_POSITION_TEXTURE_GRAY_NO_MVP = "#ShaderETC1ASPositionTextureGray_noMVP";
  66. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR = "ShaderPositionTextureColor";
  67. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP = "ShaderPositionTextureColor_noMVP";
  68. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST = "ShaderPositionTextureColorAlphaTest";
  69. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST_NO_MV = "ShaderPositionTextureColorAlphaTest_NoMV";
  70. const char* GLProgram::SHADER_NAME_POSITION_COLOR = "ShaderPositionColor";
  71. const char* GLProgram::SHADER_NAME_POSITION_COLOR_TEXASPOINTSIZE = "ShaderPositionColorTexAsPointsize";
  72. const char* GLProgram::SHADER_NAME_POSITION_COLOR_NO_MVP = "ShaderPositionColor_noMVP";
  73. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE = "ShaderPositionTexture";
  74. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_U_COLOR = "ShaderPositionTexture_uColor";
  75. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR = "ShaderPositionTextureA8Color";
  76. const char* GLProgram::SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor";
  77. const char* GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR = "ShaderPositionLengthTextureColor";
  78. const char* GLProgram::SHADER_NAME_POSITION_GRAYSCALE = "ShaderUIGrayScale";
  79. const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL = "ShaderLabelDFNormal";
  80. const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_GLOW = "ShaderLabelDFGlow";
  81. const char* GLProgram::SHADER_NAME_LABEL_NORMAL = "ShaderLabelNormal";
  82. const char* GLProgram::SHADER_NAME_LABEL_OUTLINE = "ShaderLabelOutline";
  83. const char* GLProgram::SHADER_3D_POSITION = "Shader3DPosition";
  84. const char* GLProgram::SHADER_3D_POSITION_TEXTURE = "Shader3DPositionTexture";
  85. const char* GLProgram::SHADER_3D_SKINPOSITION_TEXTURE = "Shader3DSkinPositionTexture";
  86. const char* GLProgram::SHADER_3D_POSITION_NORMAL = "Shader3DPositionNormal";
  87. const char* GLProgram::SHADER_3D_POSITION_NORMAL_TEXTURE = "Shader3DPositionNormalTexture";
  88. const char* GLProgram::SHADER_3D_SKINPOSITION_NORMAL_TEXTURE = "Shader3DSkinPositionNormalTexture";
  89. const char* GLProgram::SHADER_3D_POSITION_BUMPEDNORMAL_TEXTURE = "Shader3DPositionBumpedNormalTexture";
  90. const char* GLProgram::SHADER_3D_SKINPOSITION_BUMPEDNORMAL_TEXTURE = "Shader3DSkinPositionBumpedNormalTexture";
  91. const char* GLProgram::SHADER_3D_PARTICLE_COLOR = "Shader3DParticleColor";
  92. const char* GLProgram::SHADER_3D_PARTICLE_TEXTURE = "Shader3DParticleTexture";
  93. const char* GLProgram::SHADER_3D_SKYBOX = "Shader3DSkybox";
  94. const char* GLProgram::SHADER_3D_TERRAIN = "Shader3DTerrain";
  95. const char* GLProgram::SHADER_CAMERA_CLEAR = "ShaderCameraClear";
  96. // uniform names
  97. const char* GLProgram::UNIFORM_NAME_AMBIENT_COLOR = "CC_AmbientColor";
  98. const char* GLProgram::UNIFORM_NAME_P_MATRIX = "CC_PMatrix";
  99. const char* GLProgram::UNIFORM_NAME_MULTIVIEW_P_MATRIX = "CC_MultiViewPMatrix";
  100. const char* GLProgram::UNIFORM_NAME_MV_MATRIX = "CC_MVMatrix";
  101. const char* GLProgram::UNIFORM_NAME_MVP_MATRIX = "CC_MVPMatrix";
  102. const char* GLProgram::UNIFORM_NAME_MULTIVIEW_MVP_MATRIX = "CC_MultiViewMVPMatrix";
  103. const char* GLProgram::UNIFORM_NAME_NORMAL_MATRIX = "CC_NormalMatrix";
  104. const char* GLProgram::UNIFORM_NAME_TIME = "CC_Time";
  105. const char* GLProgram::UNIFORM_NAME_SIN_TIME = "CC_SinTime";
  106. const char* GLProgram::UNIFORM_NAME_COS_TIME = "CC_CosTime";
  107. const char* GLProgram::UNIFORM_NAME_RANDOM01 = "CC_Random01";
  108. const char* GLProgram::UNIFORM_NAME_SAMPLER0 = "CC_Texture0";
  109. const char* GLProgram::UNIFORM_NAME_SAMPLER1 = "CC_Texture1";
  110. const char* GLProgram::UNIFORM_NAME_SAMPLER2 = "CC_Texture2";
  111. const char* GLProgram::UNIFORM_NAME_SAMPLER3 = "CC_Texture3";
  112. const char* GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE = "CC_alpha_value";
  113. // Attribute names
  114. const char* GLProgram::ATTRIBUTE_NAME_COLOR = "a_color";
  115. const char* GLProgram::ATTRIBUTE_NAME_POSITION = "a_position";
  116. const char* GLProgram::ATTRIBUTE_NAME_TEX_COORD = "a_texCoord";
  117. const char* GLProgram::ATTRIBUTE_NAME_TEX_COORD1 = "a_texCoord1";
  118. const char* GLProgram::ATTRIBUTE_NAME_TEX_COORD2 = "a_texCoord2";
  119. const char* GLProgram::ATTRIBUTE_NAME_TEX_COORD3 = "a_texCoord3";
  120. const char* GLProgram::ATTRIBUTE_NAME_NORMAL = "a_normal";
  121. const char* GLProgram::ATTRIBUTE_NAME_BLEND_WEIGHT = "a_blendWeight";
  122. const char* GLProgram::ATTRIBUTE_NAME_BLEND_INDEX = "a_blendIndex";
  123. const char* GLProgram::ATTRIBUTE_NAME_TANGENT = "a_tangent";
  124. const char* GLProgram::ATTRIBUTE_NAME_BINORMAL = "a_binormal";
  125. static const char * COCOS2D_SHADER_UNIFORMS =
  126. "uniform mat4 CC_PMatrix;\n"
  127. "uniform mat4 CC_MultiViewPMatrix[4];\n"
  128. "uniform mat4 CC_MVMatrix;\n"
  129. "uniform mat4 CC_MVPMatrix;\n"
  130. "uniform mat4 CC_MultiViewMVPMatrix[4];\n"
  131. "uniform mat3 CC_NormalMatrix;\n"
  132. "uniform vec4 CC_Time;\n"
  133. "uniform vec4 CC_SinTime;\n"
  134. "uniform vec4 CC_CosTime;\n"
  135. "uniform vec4 CC_Random01;\n"
  136. "uniform sampler2D CC_Texture0;\n"
  137. "uniform sampler2D CC_Texture1;\n"
  138. "uniform sampler2D CC_Texture2;\n"
  139. "uniform sampler2D CC_Texture3;\n"
  140. "//CC INCLUDES END\n\n";
  141. static const std::string EMPTY_DEFINE;
  142. GLProgram* GLProgram::createWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray)
  143. {
  144. return createWithByteArrays(vShaderByteArray, fShaderByteArray, EMPTY_DEFINE);
  145. }
  146. GLProgram* GLProgram::createWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray, const std::string& compileTimeDefines)
  147. {
  148. return createWithByteArrays(vShaderByteArray, fShaderByteArray, EMPTY_DEFINE, compileTimeDefines);
  149. }
  150. GLProgram* GLProgram::createWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray, const std::string& compileTimeHeaders, const std::string& compileTimeDefines)
  151. {
  152. auto ret = new (std::nothrow) GLProgram();
  153. if(ret && ret->initWithByteArrays(vShaderByteArray, fShaderByteArray, compileTimeHeaders, compileTimeDefines)) {
  154. ret->link();
  155. ret->updateUniforms();
  156. ret->autorelease();
  157. return ret;
  158. }
  159. CC_SAFE_DELETE(ret);
  160. return nullptr;
  161. }
  162. GLProgram* GLProgram::createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename)
  163. {
  164. return createWithFilenames(vShaderFilename, fShaderFilename, EMPTY_DEFINE);
  165. }
  166. GLProgram* GLProgram::createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename, const std::string& compileTimeDefines)
  167. {
  168. return createWithFilenames(vShaderFilename, fShaderFilename, EMPTY_DEFINE, compileTimeDefines);
  169. }
  170. GLProgram* GLProgram::createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename, const std::string& /*compileTimeHeaders*/, const std::string& compileTimeDefines)
  171. {
  172. auto ret = new (std::nothrow) GLProgram();
  173. if(ret && ret->initWithFilenames(vShaderFilename, fShaderFilename, compileTimeDefines)) {
  174. ret->link();
  175. ret->updateUniforms();
  176. ret->autorelease();
  177. return ret;
  178. }
  179. CC_SAFE_DELETE(ret);
  180. return nullptr;
  181. }
  182. GLProgram::GLProgram()
  183. : _program(0)
  184. , _vertShader(0)
  185. , _fragShader(0)
  186. , _flags()
  187. {
  188. _director = Director::getInstance();
  189. CCASSERT(nullptr != _director, "Director is null when init a GLProgram");
  190. memset(_builtInUniforms, 0, sizeof(_builtInUniforms));
  191. }
  192. GLProgram::~GLProgram()
  193. {
  194. CCLOGINFO("%s %d deallocing GLProgram: %p", __FUNCTION__, __LINE__, this);
  195. clearShader();
  196. if (_program)
  197. {
  198. GL::deleteProgram(_program);
  199. }
  200. clearHashUniforms();
  201. }
  202. bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray)
  203. {
  204. return initWithByteArrays(vShaderByteArray, fShaderByteArray, EMPTY_DEFINE);
  205. }
  206. bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray, const std::string& compileTimeDefines)
  207. {
  208. return initWithByteArrays(vShaderByteArray, fShaderByteArray, "", compileTimeDefines);
  209. }
  210. bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray, const std::string& compileTimeHeaders, const std::string& compileTimeDefines)
  211. {
  212. _program = glCreateProgram();
  213. CHECK_GL_ERROR_DEBUG();
  214. // convert defines here. If we do it in "compileShader" we will do it twice.
  215. // a cache for the defines could be useful, but seems like overkill at this point
  216. std::string replacedDefines = "";
  217. replaceDefines(compileTimeDefines, replacedDefines);
  218. _vertShader = _fragShader = 0;
  219. if (vShaderByteArray)
  220. {
  221. if (!compileShader(&_vertShader, GL_VERTEX_SHADER, vShaderByteArray, compileTimeHeaders, replacedDefines))
  222. {
  223. CCLOG("cocos2d: ERROR: Failed to compile vertex shader");
  224. return false;
  225. }
  226. }
  227. // Create and compile fragment shader
  228. if (fShaderByteArray)
  229. {
  230. if (!compileShader(&_fragShader, GL_FRAGMENT_SHADER, fShaderByteArray, compileTimeHeaders, replacedDefines))
  231. {
  232. CCLOG("cocos2d: ERROR: Failed to compile fragment shader");
  233. return false;
  234. }
  235. }
  236. if (_vertShader)
  237. {
  238. glAttachShader(_program, _vertShader);
  239. }
  240. CHECK_GL_ERROR_DEBUG();
  241. if (_fragShader)
  242. {
  243. glAttachShader(_program, _fragShader);
  244. }
  245. clearHashUniforms();
  246. CHECK_GL_ERROR_DEBUG();
  247. return true;
  248. }
  249. bool GLProgram::initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename)
  250. {
  251. return initWithFilenames(vShaderFilename, fShaderFilename, EMPTY_DEFINE);
  252. }
  253. bool GLProgram::initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename, const std::string& compileTimeDefines)
  254. {
  255. return initWithFilenames(vShaderFilename, fShaderFilename, EMPTY_DEFINE, compileTimeDefines);
  256. }
  257. bool GLProgram::initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename, const std::string& compileTimeHeaders, const std::string& compileTimeDefines)
  258. {
  259. auto fileUtils = FileUtils::getInstance();
  260. std::string vertexSource = fileUtils->getStringFromFile(FileUtils::getInstance()->fullPathForFilename(vShaderFilename));
  261. std::string fragmentSource = fileUtils->getStringFromFile(FileUtils::getInstance()->fullPathForFilename(fShaderFilename));
  262. return initWithByteArrays(vertexSource.c_str(), fragmentSource.c_str(), compileTimeHeaders, compileTimeDefines);
  263. }
  264. void GLProgram::bindPredefinedVertexAttribs()
  265. {
  266. static const struct {
  267. const char *attributeName;
  268. int location;
  269. } attribute_locations[] =
  270. {
  271. {GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION},
  272. {GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR},
  273. {GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORD},
  274. {GLProgram::ATTRIBUTE_NAME_TEX_COORD1, GLProgram::VERTEX_ATTRIB_TEX_COORD1},
  275. {GLProgram::ATTRIBUTE_NAME_TEX_COORD2, GLProgram::VERTEX_ATTRIB_TEX_COORD2},
  276. {GLProgram::ATTRIBUTE_NAME_TEX_COORD3, GLProgram::VERTEX_ATTRIB_TEX_COORD3},
  277. {GLProgram::ATTRIBUTE_NAME_NORMAL, GLProgram::VERTEX_ATTRIB_NORMAL},
  278. };
  279. const int size = sizeof(attribute_locations) / sizeof(attribute_locations[0]);
  280. for(int i=0; i<size;i++) {
  281. glBindAttribLocation(_program, attribute_locations[i].location, attribute_locations[i].attributeName);
  282. }
  283. }
  284. void GLProgram::parseVertexAttribs()
  285. {
  286. //_vertexAttribs.clear();
  287. // Query and store vertex attribute meta-data from the program.
  288. GLint activeAttributes;
  289. GLint length;
  290. glGetProgramiv(_program, GL_ACTIVE_ATTRIBUTES, &activeAttributes);
  291. if(activeAttributes > 0)
  292. {
  293. VertexAttrib attribute;
  294. glGetProgramiv(_program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length);
  295. if(length > 0)
  296. {
  297. GLchar* attribName = (GLchar*) alloca(length + 1);
  298. for(int i = 0; i < activeAttributes; ++i)
  299. {
  300. // Query attribute info.
  301. glGetActiveAttrib(_program, i, length, nullptr, &attribute.size, &attribute.type, attribName);
  302. attribName[length] = '\0';
  303. attribute.name = std::string(attribName);
  304. // Query the pre-assigned attribute location
  305. attribute.index = glGetAttribLocation(_program, attribName);
  306. _vertexAttribs[attribute.name] = attribute;
  307. }
  308. }
  309. }
  310. else
  311. {
  312. GLchar ErrorLog[1024];
  313. glGetProgramInfoLog(_program, sizeof(ErrorLog), nullptr, ErrorLog);
  314. CCLOG("Error linking shader program: '%s'\n", ErrorLog);
  315. }
  316. }
  317. void GLProgram::parseUniforms()
  318. {
  319. //_userUniforms.clear();
  320. // Query and store uniforms from the program.
  321. GLint activeUniforms;
  322. glGetProgramiv(_program, GL_ACTIVE_UNIFORMS, &activeUniforms);
  323. if(activeUniforms > 0)
  324. {
  325. GLint length;
  326. glGetProgramiv(_program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &length);
  327. if(length > 0)
  328. {
  329. Uniform uniform;
  330. GLchar* uniformName = (GLchar*)alloca(length + 1);
  331. for(int i = 0; i < activeUniforms; ++i)
  332. {
  333. // Query uniform info.
  334. glGetActiveUniform(_program, i, length, nullptr, &uniform.size, &uniform.type, uniformName);
  335. uniformName[length] = '\0';
  336. // Only add uniforms that are not built-in.
  337. // The ones that start with 'CC_' are built-ins
  338. if(strncmp("CC_", uniformName, 3) != 0) {
  339. // remove possible array '[]' from uniform name
  340. if(length > 3)
  341. {
  342. char* c = strrchr(uniformName, '[');
  343. if(c)
  344. {
  345. *c = '\0';
  346. }
  347. }
  348. uniform.name = std::string(uniformName);
  349. uniform.location = glGetUniformLocation(_program, uniformName);
  350. GLenum __gl_error_code = glGetError();
  351. if (__gl_error_code != GL_NO_ERROR)
  352. {
  353. CCLOG("error: 0x%x uniformName: %s", (int)__gl_error_code, uniformName);
  354. }
  355. assert(__gl_error_code == GL_NO_ERROR);
  356. _userUniforms[uniform.name] = uniform;
  357. }
  358. }
  359. }
  360. }
  361. else
  362. {
  363. GLchar ErrorLog[1024];
  364. glGetProgramInfoLog(_program, sizeof(ErrorLog), nullptr, ErrorLog);
  365. CCLOG("Error linking shader program: '%s'\n", ErrorLog);
  366. }
  367. }
  368. Uniform* GLProgram::getUniform(const std::string &name)
  369. {
  370. const auto itr = _userUniforms.find(name);
  371. if( itr != _userUniforms.end())
  372. return &itr->second;
  373. return nullptr;
  374. }
  375. VertexAttrib* GLProgram::getVertexAttrib(const std::string &name)
  376. {
  377. const auto itr = _vertexAttribs.find(name);
  378. if( itr != _vertexAttribs.end())
  379. return &itr->second;
  380. return nullptr;
  381. }
  382. std::string GLProgram::getDescription() const
  383. {
  384. return StringUtils::format("<GLProgram = "
  385. CC_FORMAT_PRINTF_SIZE_T
  386. " | Program = %i, VertexShader = %i, FragmentShader = %i>",
  387. (size_t)this, _program, _vertShader, _fragShader);
  388. }
  389. bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source)
  390. {
  391. return compileShader(shader, type, source, "");
  392. }
  393. bool GLProgram::compileShader(GLuint* shader, GLenum type, const GLchar* source, const std::string& convertedDefines)
  394. {
  395. return compileShader(shader, type, source, "", convertedDefines);
  396. }
  397. bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source, const std::string& compileTimeHeaders, const std::string& convertedDefines)
  398. {
  399. GLint status;
  400. if (!source)
  401. {
  402. return false;
  403. }
  404. std::string headersDef;
  405. if (compileTimeHeaders.empty()) {
  406. #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT
  407. headersDef = (type == GL_VERTEX_SHADER ? "precision mediump float;\n precision mediump int;\n" : "precision mediump float;\n precision mediump int;\n");
  408. #elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 && CC_TARGET_PLATFORM != CC_PLATFORM_LINUX && CC_TARGET_PLATFORM != CC_PLATFORM_MAC)
  409. headersDef = (type == GL_VERTEX_SHADER ? "precision highp float;\n precision highp int;\n" : "precision mediump float;\n precision mediump int;\n");
  410. #endif
  411. }else{
  412. headersDef = compileTimeHeaders;
  413. }
  414. const GLchar *sources[] = {
  415. headersDef.c_str(),
  416. COCOS2D_SHADER_UNIFORMS,
  417. convertedDefines.c_str(),
  418. source};
  419. *shader = glCreateShader(type);
  420. glShaderSource(*shader, sizeof(sources)/sizeof(*sources), sources, nullptr);
  421. glCompileShader(*shader);
  422. glGetShaderiv(*shader, GL_COMPILE_STATUS, &status);
  423. if (! status)
  424. {
  425. GLsizei length;
  426. glGetShaderiv(*shader, GL_SHADER_SOURCE_LENGTH, &length);
  427. GLchar* src = (GLchar *)malloc(sizeof(GLchar) * length);
  428. glGetShaderSource(*shader, length, nullptr, src);
  429. CCLOG("cocos2d: ERROR: Failed to compile shader:\n%s", src);
  430. if (type == GL_VERTEX_SHADER)
  431. {
  432. CCLOG("cocos2d: %s", getVertexShaderLog().c_str());
  433. }
  434. else
  435. {
  436. CCLOG("cocos2d: %s", getFragmentShaderLog().c_str());
  437. }
  438. free(src);
  439. return false;
  440. }
  441. return (status == GL_TRUE);
  442. }
  443. GLint GLProgram::getAttribLocation(const std::string &attributeName) const
  444. {
  445. return glGetAttribLocation(_program, attributeName.c_str());
  446. }
  447. GLint GLProgram::getUniformLocation(const std::string &attributeName) const
  448. {
  449. return glGetUniformLocation(_program, attributeName.c_str());
  450. }
  451. void GLProgram::bindAttribLocation(const std::string &attributeName, GLuint index) const
  452. {
  453. glBindAttribLocation(_program, index, attributeName.c_str());
  454. }
  455. void GLProgram::updateUniforms()
  456. {
  457. _builtInUniforms[UNIFORM_AMBIENT_COLOR] = glGetUniformLocation(_program, UNIFORM_NAME_AMBIENT_COLOR);
  458. _builtInUniforms[UNIFORM_P_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_P_MATRIX);
  459. _builtInUniforms[UNIFORM_MULTIVIEW_P_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MULTIVIEW_P_MATRIX);
  460. _builtInUniforms[UNIFORM_MV_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MV_MATRIX);
  461. _builtInUniforms[UNIFORM_MVP_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MVP_MATRIX);
  462. _builtInUniforms[UNIFORM_MULTIVIEW_MVP_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MULTIVIEW_MVP_MATRIX);
  463. _builtInUniforms[UNIFORM_NORMAL_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_NORMAL_MATRIX);
  464. _builtInUniforms[UNIFORM_TIME] = glGetUniformLocation(_program, UNIFORM_NAME_TIME);
  465. _builtInUniforms[UNIFORM_SIN_TIME] = glGetUniformLocation(_program, UNIFORM_NAME_SIN_TIME);
  466. _builtInUniforms[UNIFORM_COS_TIME] = glGetUniformLocation(_program, UNIFORM_NAME_COS_TIME);
  467. _builtInUniforms[UNIFORM_RANDOM01] = glGetUniformLocation(_program, UNIFORM_NAME_RANDOM01);
  468. _builtInUniforms[UNIFORM_SAMPLER0] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER0);
  469. _builtInUniforms[UNIFORM_SAMPLER1] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER1);
  470. _builtInUniforms[UNIFORM_SAMPLER2] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER2);
  471. _builtInUniforms[UNIFORM_SAMPLER3] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER3);
  472. _flags.usesP = _builtInUniforms[UNIFORM_P_MATRIX] != -1;
  473. _flags.usesMultiViewP = _builtInUniforms[UNIFORM_MULTIVIEW_P_MATRIX] != -1;
  474. _flags.usesMV = _builtInUniforms[UNIFORM_MV_MATRIX] != -1;
  475. _flags.usesMVP = _builtInUniforms[UNIFORM_MVP_MATRIX] != -1;
  476. _flags.usesMultiViewMVP = _builtInUniforms[UNIFORM_MULTIVIEW_MVP_MATRIX] != -1;
  477. _flags.usesNormal = _builtInUniforms[UNIFORM_NORMAL_MATRIX] != -1;
  478. _flags.usesTime = (
  479. _builtInUniforms[UNIFORM_TIME] != -1 ||
  480. _builtInUniforms[UNIFORM_SIN_TIME] != -1 ||
  481. _builtInUniforms[UNIFORM_COS_TIME] != -1
  482. );
  483. _flags.usesRandom = _builtInUniforms[UNIFORM_RANDOM01] != -1;
  484. this->use();
  485. // Since sample most probably won't change, set it to 0,1,2,3 now.
  486. if(_builtInUniforms[UNIFORM_SAMPLER0] != -1)
  487. setUniformLocationWith1i(_builtInUniforms[UNIFORM_SAMPLER0], 0);
  488. if(_builtInUniforms[UNIFORM_SAMPLER1] != -1)
  489. setUniformLocationWith1i(_builtInUniforms[UNIFORM_SAMPLER1], 1);
  490. if(_builtInUniforms[UNIFORM_SAMPLER2] != -1)
  491. setUniformLocationWith1i(_builtInUniforms[UNIFORM_SAMPLER2], 2);
  492. if(_builtInUniforms[UNIFORM_SAMPLER3] != -1)
  493. setUniformLocationWith1i(_builtInUniforms[UNIFORM_SAMPLER3], 3);
  494. // clear any glErrors created by any not found uniforms
  495. glGetError();
  496. }
  497. bool GLProgram::link()
  498. {
  499. CCASSERT(_program != 0, "Cannot link invalid program");
  500. GLint status = GL_TRUE;
  501. bindPredefinedVertexAttribs();
  502. glLinkProgram(_program);
  503. // Calling glGetProgramiv(...GL_LINK_STATUS...) will force linking of the program at this moment.
  504. // Otherwise, they might be linked when they are used for the first time. (I guess this depends on the driver implementation)
  505. // So it might slow down the "booting" process on certain devices. But, on the other hand it is important to know if the shader
  506. // linked successfully. Some shaders might be downloaded in runtime so, release version should have this check.
  507. // For more info, see Github issue #16231
  508. glGetProgramiv(_program, GL_LINK_STATUS, &status);
  509. if (status == GL_FALSE)
  510. {
  511. CCLOG("cocos2d: ERROR: Failed to link program: %i", _program);
  512. GL::deleteProgram(_program);
  513. _program = 0;
  514. }
  515. else
  516. {
  517. parseVertexAttribs();
  518. parseUniforms();
  519. clearShader();
  520. }
  521. return (status == GL_TRUE);
  522. }
  523. void GLProgram::use()
  524. {
  525. GL::useProgram(_program);
  526. }
  527. static std::string logForOpenGLShader(GLuint shader)
  528. {
  529. GLint logLength = 0;
  530. glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);
  531. if (logLength < 1)
  532. return "";
  533. char *logBytes = (char*)malloc(sizeof(char) * logLength);
  534. glGetShaderInfoLog(shader, logLength, nullptr, logBytes);
  535. std::string ret(logBytes);
  536. free(logBytes);
  537. return ret;
  538. }
  539. static std::string logForOpenGLProgram(GLuint program)
  540. {
  541. GLint logLength = 0;
  542. glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength);
  543. if (logLength < 1)
  544. return "";
  545. char *logBytes = (char*)malloc(sizeof(char) * logLength);
  546. glGetProgramInfoLog(program, logLength, nullptr, logBytes);
  547. std::string ret(logBytes);
  548. free(logBytes);
  549. return ret;
  550. }
  551. std::string GLProgram::getVertexShaderLog() const
  552. {
  553. return cocos2d::logForOpenGLShader(_vertShader);
  554. }
  555. std::string GLProgram::getFragmentShaderLog() const
  556. {
  557. return cocos2d::logForOpenGLShader(_fragShader);
  558. }
  559. std::string GLProgram::getProgramLog() const
  560. {
  561. return logForOpenGLProgram(_program);
  562. }
  563. // Uniform cache
  564. bool GLProgram::updateUniformLocation(GLint location, const GLvoid* data, unsigned int bytes)
  565. {
  566. if (location < 0)
  567. {
  568. return false;
  569. }
  570. bool updated = true;
  571. auto element = _hashForUniforms.find(location);
  572. if (element == _hashForUniforms.end())
  573. {
  574. GLvoid* value = malloc(bytes);
  575. memcpy(value, data, bytes );
  576. _hashForUniforms.emplace(location, std::make_pair(value, bytes));
  577. }
  578. else
  579. {
  580. if (element->second.second < bytes)
  581. {
  582. GLvoid* value = realloc(element->second.first, bytes);
  583. memcpy(value, data, bytes);
  584. _hashForUniforms[location] = std::make_pair(value, bytes);
  585. }
  586. else
  587. {
  588. if (memcmp(element->second.first, data, bytes) == 0)
  589. {
  590. updated = false;
  591. }
  592. else
  593. memcpy(element->second.first, data, bytes);
  594. }
  595. }
  596. return updated;
  597. }
  598. GLint GLProgram::getUniformLocationForName(const char* name) const
  599. {
  600. CCASSERT(name != nullptr, "Invalid uniform name" );
  601. CCASSERT(_program != 0, "Invalid operation. Cannot get uniform location when program is not initialized");
  602. return glGetUniformLocation(_program, name);
  603. }
  604. void GLProgram::setUniformLocationWith1i(GLint location, GLint i1)
  605. {
  606. bool updated = updateUniformLocation(location, &i1, sizeof(i1)*1);
  607. if (updated)
  608. {
  609. glUniform1i( (GLint)location, i1);
  610. }
  611. }
  612. void GLProgram::setUniformLocationWith2i(GLint location, GLint i1, GLint i2)
  613. {
  614. GLint ints[2] = {i1,i2};
  615. bool updated = updateUniformLocation(location, ints, sizeof(ints));
  616. if (updated)
  617. {
  618. glUniform2i( (GLint)location, i1, i2);
  619. }
  620. }
  621. void GLProgram::setUniformLocationWith3i(GLint location, GLint i1, GLint i2, GLint i3)
  622. {
  623. GLint ints[3] = {i1,i2,i3};
  624. bool updated = updateUniformLocation(location, ints, sizeof(ints));
  625. if (updated)
  626. {
  627. glUniform3i( (GLint)location, i1, i2, i3);
  628. }
  629. }
  630. void GLProgram::setUniformLocationWith4i(GLint location, GLint i1, GLint i2, GLint i3, GLint i4)
  631. {
  632. GLint ints[4] = {i1,i2,i3,i4};
  633. bool updated = updateUniformLocation(location, ints, sizeof(ints));
  634. if (updated)
  635. {
  636. glUniform4i( (GLint)location, i1, i2, i3, i4);
  637. }
  638. }
  639. void GLProgram::setUniformLocationWith2iv(GLint location, GLint* ints, unsigned int numberOfArrays)
  640. {
  641. bool updated = updateUniformLocation(location, ints, sizeof(int)*2*numberOfArrays);
  642. if (updated)
  643. {
  644. glUniform2iv( (GLint)location, (GLsizei)numberOfArrays, ints );
  645. }
  646. }
  647. void GLProgram::setUniformLocationWith3iv(GLint location, GLint* ints, unsigned int numberOfArrays)
  648. {
  649. bool updated = updateUniformLocation(location, ints, sizeof(int)*3*numberOfArrays);
  650. if (updated)
  651. {
  652. glUniform3iv( (GLint)location, (GLsizei)numberOfArrays, ints );
  653. }
  654. }
  655. void GLProgram::setUniformLocationWith4iv(GLint location, GLint* ints, unsigned int numberOfArrays)
  656. {
  657. bool updated = updateUniformLocation(location, ints, sizeof(int)*4*numberOfArrays);
  658. if (updated)
  659. {
  660. glUniform4iv( (GLint)location, (GLsizei)numberOfArrays, ints );
  661. }
  662. }
  663. void GLProgram::setUniformLocationWith1f(GLint location, GLfloat f1)
  664. {
  665. bool updated = updateUniformLocation(location, &f1, sizeof(f1)*1);
  666. if (updated)
  667. {
  668. glUniform1f( (GLint)location, f1);
  669. }
  670. }
  671. void GLProgram::setUniformLocationWith2f(GLint location, GLfloat f1, GLfloat f2)
  672. {
  673. GLfloat floats[2] = {f1,f2};
  674. bool updated = updateUniformLocation(location, floats, sizeof(floats));
  675. if (updated)
  676. {
  677. glUniform2f( (GLint)location, f1, f2);
  678. }
  679. }
  680. void GLProgram::setUniformLocationWith3f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3)
  681. {
  682. GLfloat floats[3] = {f1,f2,f3};
  683. bool updated = updateUniformLocation(location, floats, sizeof(floats));
  684. if (updated)
  685. {
  686. glUniform3f( (GLint)location, f1, f2, f3);
  687. }
  688. }
  689. void GLProgram::setUniformLocationWith4f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4)
  690. {
  691. GLfloat floats[4] = {f1,f2,f3,f4};
  692. bool updated = updateUniformLocation(location, floats, sizeof(floats));
  693. if (updated)
  694. {
  695. glUniform4f( (GLint)location, f1, f2, f3,f4);
  696. }
  697. }
  698. void GLProgram::setUniformLocationWith1fv( GLint location, const GLfloat* floats, unsigned int numberOfArrays )
  699. {
  700. bool updated = updateUniformLocation(location, floats, sizeof(float)*numberOfArrays);
  701. if (updated)
  702. {
  703. glUniform1fv( (GLint)location, (GLsizei)numberOfArrays, floats );
  704. }
  705. }
  706. void GLProgram::setUniformLocationWith2fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays)
  707. {
  708. bool updated = updateUniformLocation(location, floats, sizeof(float)*2*numberOfArrays);
  709. if (updated)
  710. {
  711. glUniform2fv( (GLint)location, (GLsizei)numberOfArrays, floats );
  712. }
  713. }
  714. void GLProgram::setUniformLocationWith3fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays)
  715. {
  716. bool updated = updateUniformLocation(location, floats, sizeof(float)*3*numberOfArrays);
  717. if (updated)
  718. {
  719. glUniform3fv( (GLint)location, (GLsizei)numberOfArrays, floats );
  720. }
  721. }
  722. void GLProgram::setUniformLocationWith4fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays)
  723. {
  724. bool updated = updateUniformLocation(location, floats, sizeof(float)*4*numberOfArrays);
  725. if (updated)
  726. {
  727. glUniform4fv( (GLint)location, (GLsizei)numberOfArrays, floats );
  728. }
  729. }
  730. void GLProgram::setUniformLocationWithMatrix2fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) {
  731. bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*4*numberOfMatrices);
  732. if (updated)
  733. {
  734. glUniformMatrix2fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray);
  735. }
  736. }
  737. void GLProgram::setUniformLocationWithMatrix3fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) {
  738. bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*9*numberOfMatrices);
  739. if (updated)
  740. {
  741. glUniformMatrix3fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray);
  742. }
  743. }
  744. void GLProgram::setUniformLocationWithMatrix4fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices)
  745. {
  746. bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*16*numberOfMatrices);
  747. if (updated)
  748. {
  749. glUniformMatrix4fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray);
  750. }
  751. }
  752. void GLProgram::setUniformsForBuiltins()
  753. {
  754. setUniformsForBuiltins(_director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW));
  755. }
  756. void GLProgram::setUniformsForBuiltins(const Mat4 &matrixMV)
  757. {
  758. const auto& matrixP = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
  759. if (_flags.usesP)
  760. setUniformLocationWithMatrix4fv(_builtInUniforms[UNIFORM_P_MATRIX], matrixP.m, 1);
  761. if (_flags.usesMultiViewP)
  762. {
  763. Mat4 mats[4];
  764. const auto stackSize = std::min<size_t>(_director->getProjectionMatrixStackSize(), 4);
  765. for (size_t i = 0; i < stackSize; ++i) {
  766. mats[i] = _director->getProjectionMatrix(i);
  767. }
  768. setUniformLocationWithMatrix4fv(_builtInUniforms[UNIFORM_MULTIVIEW_P_MATRIX], mats[0].m, 4);
  769. }
  770. if (_flags.usesMV)
  771. setUniformLocationWithMatrix4fv(_builtInUniforms[UNIFORM_MV_MATRIX], matrixMV.m, 1);
  772. if (_flags.usesMVP)
  773. {
  774. Mat4 matrixMVP = matrixP * matrixMV;
  775. setUniformLocationWithMatrix4fv(_builtInUniforms[UNIFORM_MVP_MATRIX], matrixMVP.m, 1);
  776. }
  777. if (_flags.usesMultiViewMVP)
  778. {
  779. Mat4 mats[4];
  780. const auto stackSize = std::min<size_t>(_director->getProjectionMatrixStackSize(), 4);
  781. for (size_t i = 0; i < stackSize; ++i) {
  782. mats[i] = _director->getProjectionMatrix(i) * matrixMV;
  783. }
  784. setUniformLocationWithMatrix4fv(_builtInUniforms[UNIFORM_MULTIVIEW_MVP_MATRIX], mats[0].m, 4);
  785. }
  786. if (_flags.usesNormal)
  787. {
  788. Mat4 mvInverse = matrixMV;
  789. mvInverse.m[12] = mvInverse.m[13] = mvInverse.m[14] = 0.0f;
  790. mvInverse.inverse();
  791. mvInverse.transpose();
  792. GLfloat normalMat[9];
  793. normalMat[0] = mvInverse.m[0];normalMat[1] = mvInverse.m[1];normalMat[2] = mvInverse.m[2];
  794. normalMat[3] = mvInverse.m[4];normalMat[4] = mvInverse.m[5];normalMat[5] = mvInverse.m[6];
  795. normalMat[6] = mvInverse.m[8];normalMat[7] = mvInverse.m[9];normalMat[8] = mvInverse.m[10];
  796. setUniformLocationWithMatrix3fv(_builtInUniforms[UNIFORM_NORMAL_MATRIX], normalMat, 1);
  797. }
  798. if (_flags.usesTime) {
  799. // This doesn't give the most accurate global time value.
  800. // Cocos2D doesn't store a high precision time value, so this will have to do.
  801. // Getting Mach time per frame per shader using time could be extremely expensive.
  802. float time = _director->getTotalFrames() * _director->getAnimationInterval();
  803. setUniformLocationWith4f(_builtInUniforms[GLProgram::UNIFORM_TIME], time/10.0f, time, time*2, time*4);
  804. setUniformLocationWith4f(_builtInUniforms[GLProgram::UNIFORM_SIN_TIME], time/8.0f, time/4.0f, time/2.0f, sinf(time));
  805. setUniformLocationWith4f(_builtInUniforms[GLProgram::UNIFORM_COS_TIME], time/8.0f, time/4.0f, time/2.0f, cosf(time));
  806. }
  807. if (_flags.usesRandom)
  808. setUniformLocationWith4f(_builtInUniforms[GLProgram::UNIFORM_RANDOM01], CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1());
  809. }
  810. void GLProgram::reset()
  811. {
  812. _vertShader = _fragShader = 0;
  813. memset(_builtInUniforms, 0, sizeof(_builtInUniforms));
  814. // it is already deallocated by android
  815. //GL::deleteProgram(_program);
  816. _program = 0;
  817. clearHashUniforms();
  818. }
  819. inline void GLProgram::clearShader()
  820. {
  821. if (_vertShader)
  822. {
  823. glDeleteShader(_vertShader);
  824. }
  825. if (_fragShader)
  826. {
  827. glDeleteShader(_fragShader);
  828. }
  829. _vertShader = _fragShader = 0;
  830. }
  831. inline void GLProgram::clearHashUniforms()
  832. {
  833. for (auto e: _hashForUniforms)
  834. {
  835. free(e.second.first);
  836. }
  837. _hashForUniforms.clear();
  838. }
  839. NS_CC_END