ShaderProgram.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. #include "anki/gl/ShaderProgram.h"
  2. #include "anki/gl/GlException.h"
  3. #include "anki/gl/GlState.h"
  4. #include "anki/math/Math.h"
  5. #include "anki/util/Exception.h"
  6. #include "anki/gl/Texture.h"
  7. #include "anki/core/Logger.h"
  8. #include "anki/util/StringList.h"
  9. #include "anki/util/Array.h"
  10. #include <sstream>
  11. #include <iomanip>
  12. namespace anki {
  13. //==============================================================================
  14. static const char* padding = "======================================="
  15. "=======================================";
  16. //==============================================================================
  17. // ShaderProgramVariable =
  18. //==============================================================================
  19. //==============================================================================
  20. ShaderProgramVariable& ShaderProgramVariable::operator=(
  21. const ShaderProgramVariable& b)
  22. {
  23. ANKI_ASSERT(type == b.type);
  24. loc = b.loc;
  25. name = b.name;
  26. glDataType = b.glDataType;
  27. size = b.size;
  28. fatherSProg = b.fatherSProg;
  29. return *this;
  30. }
  31. //==============================================================================
  32. // ShaderProgramUniformVariable =
  33. //==============================================================================
  34. //==============================================================================
  35. ShaderProgramUniformVariable& ShaderProgramUniformVariable::operator=(
  36. const ShaderProgramUniformVariable& b)
  37. {
  38. ShaderProgramVariable::operator=(b);
  39. index = b.index;
  40. block = b.block;
  41. offset = b.offset;
  42. arrayStride = b.arrayStride;
  43. matrixStride = b.matrixStride;
  44. return *this;
  45. }
  46. //==============================================================================
  47. void ShaderProgramUniformVariable::doCommonSetCode() const
  48. {
  49. ANKI_ASSERT(getLocation() != -1
  50. && "You cannot set variable in uniform block");
  51. ANKI_ASSERT(ShaderProgram::getCurrentProgramGlId() ==
  52. getFatherShaderProgram().getGlId());
  53. }
  54. //==============================================================================
  55. void ShaderProgramUniformVariable::set(const F32 x) const
  56. {
  57. doCommonSetCode();
  58. ANKI_ASSERT(getGlDataType() == GL_FLOAT);
  59. ANKI_ASSERT(getSize() == 1);
  60. glUniform1f(getLocation(), x);
  61. }
  62. //==============================================================================
  63. void ShaderProgramUniformVariable::set(const Vec2& x) const
  64. {
  65. doCommonSetCode();
  66. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC2);
  67. ANKI_ASSERT(getSize() == 1);
  68. glUniform2f(getLocation(), x.x(), x.y());
  69. }
  70. //==============================================================================
  71. void ShaderProgramUniformVariable::set(const F32 x[], U32 size) const
  72. {
  73. doCommonSetCode();
  74. ANKI_ASSERT(getGlDataType() == GL_FLOAT);
  75. ANKI_ASSERT(size <= getSize() && size != 0);
  76. glUniform1fv(getLocation(), size, x);
  77. }
  78. //==============================================================================
  79. void ShaderProgramUniformVariable::set(const Vec2 x[], U32 size) const
  80. {
  81. doCommonSetCode();
  82. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC2);
  83. ANKI_ASSERT(size <= getSize() && size != 0);
  84. glUniform2fv(getLocation(), size, &(const_cast<Vec2&>(x[0]))[0]);
  85. }
  86. //==============================================================================
  87. void ShaderProgramUniformVariable::set(const Vec3 x[], U32 size) const
  88. {
  89. doCommonSetCode();
  90. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC3);
  91. ANKI_ASSERT(size <= getSize() && size != 0);
  92. glUniform3fv(getLocation(), size, &(const_cast<Vec3&>(x[0]))[0]);
  93. }
  94. //==============================================================================
  95. void ShaderProgramUniformVariable::set(const Vec4 x[], U32 size) const
  96. {
  97. doCommonSetCode();
  98. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC4);
  99. ANKI_ASSERT(size <= getSize() && size != 0);
  100. glUniform4fv(getLocation(), size, &(const_cast<Vec4&>(x[0]))[0]);
  101. }
  102. //==============================================================================
  103. void ShaderProgramUniformVariable::set(const Mat3 x[], U32 size) const
  104. {
  105. doCommonSetCode();
  106. ANKI_ASSERT(getGlDataType() == GL_FLOAT_MAT3);
  107. ANKI_ASSERT(size <= getSize() && size != 0);
  108. glUniformMatrix3fv(getLocation(), size, true, &(x[0])[0]);
  109. }
  110. //==============================================================================
  111. void ShaderProgramUniformVariable::set(const Mat4 x[], U32 size) const
  112. {
  113. doCommonSetCode();
  114. ANKI_ASSERT(getGlDataType() == GL_FLOAT_MAT4);
  115. ANKI_ASSERT(size <= getSize() && size != 0);
  116. glUniformMatrix4fv(getLocation(), size, true, &(x[0])[0]);
  117. }
  118. //==============================================================================
  119. void ShaderProgramUniformVariable::set(const Texture& tex) const
  120. {
  121. doCommonSetCode();
  122. ANKI_ASSERT(getGlDataType() == GL_SAMPLER_2D
  123. || getGlDataType() == GL_SAMPLER_2D_SHADOW
  124. || getGlDataType() == GL_UNSIGNED_INT_SAMPLER_2D
  125. || getGlDataType() == GL_SAMPLER_2D_ARRAY_SHADOW);
  126. glUniform1i(getLocation(), tex.bind());
  127. }
  128. //==============================================================================
  129. void ShaderProgramUniformVariable::set(const Texture* const texes[],
  130. const U32 count) const
  131. {
  132. doCommonSetCode();
  133. ANKI_ASSERT(count <= getSize() && count != 0);
  134. ANKI_ASSERT(count <= 128);
  135. Array<GLint, 128> units;
  136. for(U32 i = 0; i < count; i++)
  137. {
  138. const Texture* tex = texes[i];
  139. units[i] = tex->bind();
  140. }
  141. glUniform1iv(getLocation(), count, &units[0]);
  142. }
  143. //==============================================================================
  144. // Template functions that return the GL type using an AnKi type
  145. template<typename T>
  146. static Bool checkType(GLenum glDataType);
  147. template<>
  148. Bool checkType<F32>(GLenum glDataType)
  149. {
  150. return glDataType == GL_FLOAT;
  151. }
  152. template<>
  153. Bool checkType<Vec2>(GLenum glDataType)
  154. {
  155. return glDataType == GL_FLOAT_VEC2;
  156. }
  157. template<>
  158. Bool checkType<Vec3>(GLenum glDataType)
  159. {
  160. return glDataType == GL_FLOAT_VEC3;
  161. }
  162. template<>
  163. Bool checkType<Vec4>(GLenum glDataType)
  164. {
  165. return glDataType == GL_FLOAT_VEC4;
  166. }
  167. template<>
  168. Bool checkType<Mat3>(GLenum glDataType)
  169. {
  170. return glDataType == GL_FLOAT_MAT3;
  171. }
  172. template<>
  173. Bool checkType<Mat4>(GLenum glDataType)
  174. {
  175. return glDataType == GL_FLOAT_MAT4;
  176. }
  177. //==============================================================================
  178. template<typename T>
  179. void ShaderProgramUniformVariable::setClientMemorySanityChecks(
  180. U32 buffSize, U32 size) const
  181. {
  182. ANKI_ASSERT(checkType<T>(getGlDataType()));
  183. ANKI_ASSERT(size <= getSize() && size > 0);
  184. ANKI_ASSERT(offset != -1 && arrayStride != -1 && "Uniform is not in block");
  185. ANKI_ASSERT(block->getSize() <= buffSize);
  186. ANKI_ASSERT(size <= 1 || arrayStride != 0);
  187. }
  188. //==============================================================================
  189. template<typename T>
  190. void ShaderProgramUniformVariable::setClientMemoryInternal(
  191. void* buff_, U32 buffSize, const T arr[], U32 size) const
  192. {
  193. setClientMemorySanityChecks<T>(buffSize, size);
  194. U8* buff = (U8*)buff_ + offset;
  195. for(U32 i = 0; i < size; i++)
  196. {
  197. T* ptr = (T*)buff;
  198. *ptr = arr[i];
  199. buff += arrayStride;
  200. }
  201. }
  202. //==============================================================================
  203. template<typename T, typename Vec>
  204. void ShaderProgramUniformVariable::setClientMemoryInternalMatrix(
  205. void* buff_, U32 buffSize, const T arr[], U32 size) const
  206. {
  207. setClientMemorySanityChecks<T>(buffSize, size);
  208. ANKI_ASSERT(matrixStride >= (GLint)sizeof(Vec));
  209. U8* buff = (U8*)buff_ + offset;
  210. for(U32 i = 0; i < size; i++)
  211. {
  212. U8* subbuff = buff;
  213. for(U j = 0; j < sizeof(T) / sizeof(Vec); j++)
  214. {
  215. Vec* ptr = (Vec*)subbuff;
  216. *ptr = arr[i].getRow(j);
  217. subbuff += matrixStride;
  218. }
  219. buff += arrayStride;
  220. }
  221. }
  222. //==============================================================================
  223. void ShaderProgramUniformVariable::setClientMemory(void* buff, U32 buffSize,
  224. const F32 arr[], U32 size) const
  225. {
  226. setClientMemoryInternal(buff, buffSize, arr, size);
  227. }
  228. //==============================================================================
  229. void ShaderProgramUniformVariable::setClientMemory(void* buff, U32 buffSize,
  230. const Vec2 arr[], U32 size) const
  231. {
  232. setClientMemoryInternal(buff, buffSize, arr, size);
  233. }
  234. //==============================================================================
  235. void ShaderProgramUniformVariable::setClientMemory(void* buff, U32 buffSize,
  236. const Vec3 arr[], U32 size) const
  237. {
  238. setClientMemoryInternal(buff, buffSize, arr, size);
  239. }
  240. //==============================================================================
  241. void ShaderProgramUniformVariable::setClientMemory(void* buff, U32 buffSize,
  242. const Vec4 arr[], U32 size) const
  243. {
  244. setClientMemoryInternal(buff, buffSize, arr, size);
  245. }
  246. //==============================================================================
  247. void ShaderProgramUniformVariable::setClientMemory(void* buff, U32 buffSize,
  248. const Mat3 arr[], U32 size) const
  249. {
  250. setClientMemoryInternalMatrix<Mat3, Vec3>(buff, buffSize, arr, size);
  251. }
  252. //==============================================================================
  253. void ShaderProgramUniformVariable::setClientMemory(void* buff, U32 buffSize,
  254. const Mat4 arr[], U32 size) const
  255. {
  256. setClientMemoryInternalMatrix<Mat4, Vec4>(buff, buffSize, arr, size);
  257. }
  258. //==============================================================================
  259. // ShaderProgramUniformBlock =
  260. //==============================================================================
  261. //==============================================================================
  262. ShaderProgramUniformBlock& ShaderProgramUniformBlock::operator=(
  263. const ShaderProgramUniformBlock& b)
  264. {
  265. uniforms = b.uniforms;
  266. index = b.index;
  267. size = b.size;
  268. name = b.name;
  269. bindingPoint = b.bindingPoint;
  270. progId = b.progId;
  271. return *this;
  272. }
  273. //==============================================================================
  274. // ShaderProgram =
  275. //==============================================================================
  276. //==============================================================================
  277. thread_local const ShaderProgram* ShaderProgram::current = nullptr;
  278. //==============================================================================
  279. void ShaderProgram::create(const char* vertSource, const char* tcSource,
  280. const char* teSource, const char* geomSource, const char* fragSource,
  281. const char* xfbVaryings[], const GLenum xfbBufferMode)
  282. {
  283. ANKI_ASSERT(!isCreated());
  284. U32 minor = GlStateCommonSingleton::get().getMinorVersion();
  285. U32 major = GlStateCommonSingleton::get().getMajorVersion();
  286. // 1) create and compile the shaders
  287. //
  288. std::string preprocSrc;
  289. #if ANKI_GL == ANKI_GL_DESKTOP
  290. preprocSrc = "#version " + std::to_string(major)
  291. + std::to_string(minor) + "0 core\n";
  292. if(major == 3)
  293. {
  294. preprocSrc += "#extension GL_ARB_shading_language_420pack : enable\n"
  295. "#extension GL_ARB_shading_language_packing : enable\n"
  296. "#extension GL_ARB_gpu_shader5 : enable\n";
  297. }
  298. else
  299. {
  300. preprocSrc += "#extension GL_ARB_gpu_shader5 : enable\n";
  301. }
  302. #else
  303. preprocSrc = "#version " + std::to_string(major)
  304. + std::to_string(minor) + "0 es\n";
  305. #endif
  306. ANKI_ASSERT(vertSource != nullptr);
  307. vertShaderGlId = createAndCompileShader(vertSource, preprocSrc.c_str(),
  308. GL_VERTEX_SHADER);
  309. if(tcSource != nullptr)
  310. {
  311. #if ANKI_GL == ANKI_GL_DESKTOP
  312. ANKI_ASSERT(major > 3);
  313. tcShaderGlId = createAndCompileShader(tcSource, preprocSrc.c_str(),
  314. GL_TESS_CONTROL_SHADER);
  315. #else
  316. ANKI_ASSERT(0 && "Not allowed");
  317. #endif
  318. }
  319. if(teSource != nullptr)
  320. {
  321. #if ANKI_GL == ANKI_GL_DESKTOP
  322. ANKI_ASSERT(major > 3);
  323. teShaderGlId = createAndCompileShader(teSource, preprocSrc.c_str(),
  324. GL_TESS_EVALUATION_SHADER);
  325. #else
  326. ANKI_ASSERT(0 && "Not allowed");
  327. #endif
  328. }
  329. if(geomSource != nullptr)
  330. {
  331. #if ANKI_GL == ANKI_GL_DESKTOP
  332. geomShaderGlId = createAndCompileShader(geomSource,
  333. preprocSrc.c_str(), GL_GEOMETRY_SHADER);
  334. #else
  335. ANKI_ASSERT(0 && "Not allowed");
  336. #endif
  337. }
  338. ANKI_ASSERT(fragSource != nullptr);
  339. fragShaderGlId = createAndCompileShader(fragSource, preprocSrc.c_str(),
  340. GL_FRAGMENT_SHADER);
  341. // 2) create program and attach shaders
  342. glId = glCreateProgram();
  343. if(glId == 0)
  344. {
  345. throw ANKI_EXCEPTION("glCreateProgram() failed");
  346. }
  347. glAttachShader(glId, vertShaderGlId);
  348. glAttachShader(glId, fragShaderGlId);
  349. if(tcSource != nullptr)
  350. {
  351. glAttachShader(glId, tcShaderGlId);
  352. }
  353. if(teSource != nullptr)
  354. {
  355. glAttachShader(glId, teShaderGlId);
  356. }
  357. if(geomSource != nullptr)
  358. {
  359. glAttachShader(glId, geomShaderGlId);
  360. }
  361. // 3) set the XFB varyings
  362. U count = 0;
  363. if(xfbVaryings)
  364. {
  365. while(xfbVaryings[count] != nullptr)
  366. {
  367. ++count;
  368. }
  369. }
  370. if(count)
  371. {
  372. glTransformFeedbackVaryings(
  373. glId,
  374. count,
  375. xfbVaryings,
  376. xfbBufferMode);
  377. }
  378. // 4) link
  379. link();
  380. // init the rest
  381. bind();
  382. initUniAndAttribVars();
  383. initUniformBlocks();
  384. }
  385. //==============================================================================
  386. void ShaderProgram::destroy()
  387. {
  388. unbind();
  389. if(vertShaderGlId != 0)
  390. {
  391. glDeleteShader(vertShaderGlId);
  392. }
  393. if(tcShaderGlId != 0)
  394. {
  395. glDeleteShader(tcShaderGlId);
  396. }
  397. if(teShaderGlId != 0)
  398. {
  399. glDeleteShader(teShaderGlId);
  400. }
  401. if(geomShaderGlId != 0)
  402. {
  403. glDeleteShader(geomShaderGlId);
  404. }
  405. if(fragShaderGlId != 0)
  406. {
  407. glDeleteShader(fragShaderGlId);
  408. }
  409. if(glId != 0)
  410. {
  411. glDeleteProgram(glId);
  412. }
  413. init();
  414. }
  415. //==============================================================================
  416. GLuint ShaderProgram::createAndCompileShader(const char* sourceCode,
  417. const char* preproc, GLenum type)
  418. {
  419. GLuint glId = 0;
  420. const char* sourceStrs[1] = {nullptr};
  421. // create the shader
  422. glId = glCreateShader(type);
  423. // attach the source
  424. std::string fullSrc = preproc;
  425. fullSrc += sourceCode;
  426. sourceStrs[0] = fullSrc.c_str();
  427. // compile
  428. glShaderSource(glId, 1, sourceStrs, NULL);
  429. glCompileShader(glId);
  430. GLint success;
  431. glGetShaderiv(glId, GL_COMPILE_STATUS, &success);
  432. if(!success)
  433. {
  434. // Get info log
  435. GLint infoLen = 0;
  436. GLint charsWritten = 0;
  437. Vector<char> infoLog;
  438. glGetShaderiv(glId, GL_INFO_LOG_LENGTH, &infoLen);
  439. infoLog.resize(infoLen + 1);
  440. glGetShaderInfoLog(glId, infoLen, &charsWritten, &infoLog[0]);
  441. infoLog[charsWritten] = '\0';
  442. std::stringstream err;
  443. err << "Shader compile failed (0x" << std::hex << type << std::dec
  444. << "):\n" << padding << "\n" << &infoLog[0]
  445. << "\n" << padding << "\nSource:\n" << padding << "\n";
  446. // Prettyfy source
  447. StringList lines = StringList::splitString(fullSrc.c_str(), '\n', true);
  448. int lineno = 0;
  449. for(const std::string& line : lines)
  450. {
  451. err << std::setw(4) << std::setfill('0') << ++lineno << ": "
  452. << line << std::endl;
  453. }
  454. err << padding;
  455. // Throw
  456. throw ANKI_EXCEPTION(err.str());
  457. }
  458. ANKI_ASSERT(glId != 0);
  459. return glId;
  460. }
  461. //==============================================================================
  462. void ShaderProgram::link() const
  463. {
  464. // link
  465. glLinkProgram(glId);
  466. // check if linked correctly
  467. GLint success;
  468. glGetProgramiv(glId, GL_LINK_STATUS, &success);
  469. if(!success)
  470. {
  471. int info_len = 0;
  472. int charsWritten = 0;
  473. std::string infoLogTxt;
  474. glGetProgramiv(glId, GL_INFO_LOG_LENGTH, &info_len);
  475. infoLogTxt.resize(info_len + 1);
  476. glGetProgramInfoLog(glId, info_len, &charsWritten, &infoLogTxt[0]);
  477. throw ANKI_EXCEPTION("Link error log follows:\n"
  478. + infoLogTxt);
  479. }
  480. }
  481. //==============================================================================
  482. void ShaderProgram::initUniAndAttribVars()
  483. {
  484. GLint num;
  485. Array<char, 256> name_;
  486. GLsizei length;
  487. GLint size;
  488. GLenum type;
  489. //
  490. // attrib locations
  491. //
  492. glGetProgramiv(glId, GL_ACTIVE_ATTRIBUTES, &num);
  493. U32 attribsCount = (U32)num;
  494. // Count the _useful_ attribs
  495. for(GLint i = 0; i < num; i++)
  496. {
  497. // Name
  498. glGetActiveAttrib(glId, i, sizeof(name_), &length,
  499. &size, &type, &name_[0]);
  500. name_[length] = '\0';
  501. // check if its FFP location
  502. GLint loc = glGetAttribLocation(glId, &name_[0]);
  503. if(loc == -1)
  504. {
  505. // if -1 it means that its an FFP var or a weird crap like
  506. // gl_InstanceID
  507. --attribsCount;
  508. }
  509. }
  510. attribs.resize(attribsCount);
  511. attribs.shrink_to_fit();
  512. attribsCount = 0;
  513. for(GLint i = 0; i < num; i++) // loop all attributes
  514. {
  515. // Name
  516. glGetActiveAttrib(glId, i, sizeof(name_), &length,
  517. &size, &type, &name_[0]);
  518. name_[length] = '\0';
  519. // check if its FFP location
  520. GLint loc = glGetAttribLocation(glId, &name_[0]);
  521. if(loc == -1)
  522. {
  523. // if -1 it means that its an FFP var or a weird crap like
  524. // gl_InstanceID
  525. continue;
  526. }
  527. ShaderProgramAttributeVariable& var = attribs[attribsCount++];
  528. var.loc = loc;
  529. var.name = &name_[0];
  530. var.name.shrink_to_fit();
  531. var.glDataType = type;
  532. var.size = size;
  533. var.fatherSProg = this;
  534. nameToAttribVar[var.name.c_str()] = &var;
  535. }
  536. //
  537. // uni locations
  538. //
  539. glGetProgramiv(glId, GL_ACTIVE_UNIFORMS, &num);
  540. U unisCount = num;
  541. // Count the _useful_ uniforms
  542. for(GLint i = 0; i < num; i++)
  543. {
  544. glGetActiveUniform(glId, i, sizeof(name_), &length,
  545. &size, &type, &name_[0]);
  546. name_[length] = '\0';
  547. // See bellow for info
  548. if(strchr(&name_[0], '[') != nullptr
  549. && strstr(&name_[0], "[0]") == nullptr)
  550. {
  551. --unisCount;
  552. }
  553. }
  554. unis.resize(unisCount);
  555. unis.shrink_to_fit();
  556. unisCount = 0;
  557. for(GLint i = 0; i < num; i++) // loop all uniforms
  558. {
  559. glGetActiveUniform(glId, i, sizeof(name_), &length,
  560. &size, &type, &name_[0]);
  561. name_[length] = '\0';
  562. // In case of uniform arrays some implementations (nVidia) on
  563. // GL_ACTIVE_UNIFORMS they return the number of uniforms that are inside
  564. // that uniform array in addition to the first element (it will count
  565. // for example the float_arr[9]). But other implementations don't (Mali
  566. // T6xx). Also in some cases with big arrays (IS shader) this will
  567. // overpopulate the uniforms vector and hash map. So, to solve this if
  568. // the uniform name has something like this "[N]" where N != 0 then
  569. // ignore the uniform and put it as array
  570. if(strchr(&name_[0], '[') != nullptr)
  571. {
  572. // Found bracket
  573. if(strstr(&name_[0], "[0]") == nullptr)
  574. {
  575. // Found something other than "[0]"
  576. continue;
  577. }
  578. else
  579. {
  580. // Cut the bracket stuff
  581. name_[length - 3] = '\0';
  582. }
  583. }
  584. ShaderProgramUniformVariable& var = unis[unisCount++];
  585. // -1 means in uniform block
  586. GLint loc = glGetUniformLocation(glId, &name_[0]);
  587. var.loc = loc;
  588. var.name = &name_[0];
  589. var.name.shrink_to_fit();
  590. var.glDataType = type;
  591. var.size = size;
  592. var.fatherSProg = this;
  593. var.index = (GLuint)i;
  594. nameToUniVar[var.name.c_str()] = &var;
  595. }
  596. }
  597. //==============================================================================
  598. void ShaderProgram::initUniformBlocks()
  599. {
  600. // Get blocks count and create the vector
  601. GLint blocksCount;
  602. glGetProgramiv(glId, GL_ACTIVE_UNIFORM_BLOCKS, &blocksCount);
  603. if(blocksCount < 1)
  604. {
  605. // Early exit
  606. return;
  607. }
  608. blocks.resize(blocksCount);
  609. blocks.shrink_to_fit();
  610. // Init all blocks
  611. GLuint i = 0;
  612. for(ShaderProgramUniformBlock& block : blocks)
  613. {
  614. GLint gli; // General purpose int
  615. // Name
  616. Array<char, 256> name;
  617. GLsizei len;
  618. glGetActiveUniformBlockName(glId, i, sizeof(name), &len, &name[0]);
  619. // The name is null terminated
  620. block.name = &name[0];
  621. block.name.shrink_to_fit();
  622. // Index
  623. ANKI_ASSERT(glGetUniformBlockIndex(glId, name) == i);
  624. block.index = i;
  625. // Size
  626. glGetActiveUniformBlockiv(glId, i, GL_UNIFORM_BLOCK_DATA_SIZE, &gli);
  627. block.size = gli;
  628. // Binding point
  629. glGetActiveUniformBlockiv(glId, i, GL_UNIFORM_BLOCK_BINDING, &gli);
  630. block.bindingPoint = gli;
  631. // Prog id
  632. block.progId = glId;
  633. // Other update
  634. nameToBlock[block.name.c_str()] = &block;
  635. ++i;
  636. }
  637. // Connect uniforms and blocks
  638. for(ShaderProgramUniformVariable& uni : unis)
  639. {
  640. /* Block index */
  641. GLint blockIndex;
  642. glGetActiveUniformsiv(glId, 1, &(uni.index), GL_UNIFORM_BLOCK_INDEX,
  643. &blockIndex);
  644. if(blockIndex == -1)
  645. {
  646. continue;
  647. }
  648. uni.block = &blocks[blockIndex];
  649. blocks[blockIndex].uniforms.push_back(&uni);
  650. /* Offset in block */
  651. GLint offset;
  652. glGetActiveUniformsiv(glId, 1, &(uni.index), GL_UNIFORM_OFFSET,
  653. &offset);
  654. ANKI_ASSERT(offset != -1); // If -1 then it should break before
  655. uni.offset = offset;
  656. /* Array stride */
  657. GLint arrStride;
  658. glGetActiveUniformsiv(glId, 1, &(uni.index), GL_UNIFORM_ARRAY_STRIDE,
  659. &arrStride);
  660. ANKI_ASSERT(arrStride != -1); // If -1 then it should break before
  661. uni.arrayStride = arrStride;
  662. /* Matrix stride */
  663. GLint matStride;
  664. glGetActiveUniformsiv(glId, 1, &(uni.index), GL_UNIFORM_MATRIX_STRIDE,
  665. &matStride);
  666. ANKI_ASSERT(matStride != -1); // If -1 then it should break before
  667. uni.matrixStride = matStride;
  668. /* Matrix layout check */
  669. GLint isRowMajor;
  670. glGetActiveUniformsiv(glId, 1, &(uni.index), GL_UNIFORM_IS_ROW_MAJOR,
  671. &isRowMajor);
  672. if(isRowMajor)
  673. {
  674. ANKI_LOGW("The engine is designed to work with column major "
  675. "matrices: " << uni.name);
  676. }
  677. }
  678. }
  679. //==============================================================================
  680. const ShaderProgramAttributeVariable*
  681. ShaderProgram::tryFindAttributeVariable(const char* name) const
  682. {
  683. NameToAttribVarHashMap::const_iterator it = nameToAttribVar.find(name);
  684. return (it == nameToAttribVar.end()) ? nullptr : it->second;
  685. }
  686. //==============================================================================
  687. const ShaderProgramAttributeVariable&
  688. ShaderProgram::findAttributeVariable(const char* name) const
  689. {
  690. const ShaderProgramAttributeVariable* var = tryFindAttributeVariable(name);
  691. if(var == nullptr)
  692. {
  693. throw ANKI_EXCEPTION("Attribute variable not found: " + name);
  694. }
  695. return *var;
  696. }
  697. //==============================================================================
  698. const ShaderProgramUniformVariable* ShaderProgram::tryFindUniformVariable(
  699. const char* name) const
  700. {
  701. NameToUniVarHashMap::const_iterator it = nameToUniVar.find(name);
  702. if(it == nameToUniVar.end())
  703. {
  704. return nullptr;
  705. }
  706. return it->second;
  707. }
  708. //==============================================================================
  709. const ShaderProgramUniformVariable& ShaderProgram::findUniformVariable(
  710. const char* name) const
  711. {
  712. const ShaderProgramUniformVariable* var = tryFindUniformVariable(name);
  713. if(var == nullptr)
  714. {
  715. throw ANKI_EXCEPTION("Uniform variable not found: " + name);
  716. }
  717. return *var;
  718. }
  719. //==============================================================================
  720. const ShaderProgramUniformBlock* ShaderProgram::tryFindUniformBlock(
  721. const char* name) const
  722. {
  723. NameToUniformBlockHashMap::const_iterator it = nameToBlock.find(name);
  724. return (it == nameToBlock.end()) ? nullptr : it->second;
  725. }
  726. //==============================================================================
  727. const ShaderProgramUniformBlock& ShaderProgram::findUniformBlock(
  728. const char* name) const
  729. {
  730. const ShaderProgramUniformBlock* block = tryFindUniformBlock(name);
  731. if(block == nullptr)
  732. {
  733. throw ANKI_EXCEPTION("Block not found: " + name);
  734. }
  735. return *block;
  736. }
  737. //==============================================================================
  738. std::ostream& operator<<(std::ostream& s, const ShaderProgram& x)
  739. {
  740. s << "ShaderProgram\n";
  741. s << "Uniform variables:\n";
  742. for(auto var : x.unis)
  743. {
  744. s << var.getName() << " " << var.getLocation() << '\n';
  745. }
  746. s << "Attrib variables:\n";
  747. for(auto var : x.attribs)
  748. {
  749. s << var.getName() << " " << var.getLocation() << '\n';
  750. }
  751. return s;
  752. }
  753. } // end namespace anki