ShaderProgram.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. #include "anki/gl/ShaderProgram.h"
  2. #include "anki/gl/GlException.h"
  3. #include "anki/core/Logger.h"
  4. #include "anki/math/Math.h"
  5. #include "anki/util/Exception.h"
  6. #include "anki/gl/Texture.h"
  7. namespace anki {
  8. //==============================================================================
  9. // ShaderProgramVariable =
  10. //==============================================================================
  11. //==============================================================================
  12. void ShaderProgramUniformVariable::doSanityChecks() const
  13. {
  14. ANKI_ASSERT(getLocation() != -1);
  15. ANKI_ASSERT(ShaderProgram::getCurrentProgram() ==
  16. &getFatherShaderProgram());
  17. ANKI_ASSERT(glGetUniformLocation(getFatherShaderProgram().getGlId(),
  18. getName().c_str()) == getLocation());
  19. }
  20. //==============================================================================
  21. void ShaderProgramUniformVariable::set(const float x) const
  22. {
  23. doSanityChecks();
  24. ANKI_ASSERT(getGlDataType() == GL_FLOAT);
  25. ANKI_ASSERT(getSize() == 1);
  26. glUniform1f(getLocation(), x);
  27. }
  28. //==============================================================================
  29. void ShaderProgramUniformVariable::set(const Vec2& x) const
  30. {
  31. doSanityChecks();
  32. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC2);
  33. ANKI_ASSERT(getSize() == 2);
  34. glUniform2f(getLocation(), x.x(), x.y());
  35. }
  36. //==============================================================================
  37. void ShaderProgramUniformVariable::set(const float x[], uint size) const
  38. {
  39. doSanityChecks();
  40. ANKI_ASSERT(getGlDataType() == GL_FLOAT);
  41. ANKI_ASSERT(getSize() == size);
  42. glUniform1fv(getLocation(), size, x);
  43. }
  44. //==============================================================================
  45. void ShaderProgramUniformVariable::set(const Vec2 x[], uint size) const
  46. {
  47. doSanityChecks();
  48. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC2);
  49. ANKI_ASSERT(getSize() == size * 2);
  50. glUniform2fv(getLocation(), size, &(const_cast<Vec2&>(x[0]))[0]);
  51. }
  52. //==============================================================================
  53. void ShaderProgramUniformVariable::set(const Vec3 x[], uint size) const
  54. {
  55. doSanityChecks();
  56. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC3);
  57. ANKI_ASSERT(getSize() == size * 3);
  58. glUniform3fv(getLocation(), size, &(const_cast<Vec3&>(x[0]))[0]);
  59. }
  60. //==============================================================================
  61. void ShaderProgramUniformVariable::set(const Vec4 x[], uint size) const
  62. {
  63. doSanityChecks();
  64. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC4);
  65. ANKI_ASSERT(getSize() == size * 4);
  66. glUniform4fv(getLocation(), size, &(const_cast<Vec4&>(x[0]))[0]);
  67. }
  68. //==============================================================================
  69. void ShaderProgramUniformVariable::set(const Mat3 x[], uint size) const
  70. {
  71. doSanityChecks();
  72. ANKI_ASSERT(getGlDataType() == GL_FLOAT_MAT3);
  73. ANKI_ASSERT(getSize() == size);
  74. glUniformMatrix3fv(getLocation(), size, true, &(x[0])[0]);
  75. }
  76. //==============================================================================
  77. void ShaderProgramUniformVariable::set(const Mat4 x[], uint size) const
  78. {
  79. doSanityChecks();
  80. ANKI_ASSERT(getGlDataType() == GL_FLOAT_MAT4);
  81. ANKI_ASSERT(getSize() == size);
  82. glUniformMatrix4fv(getLocation(), size, true, &(x[0])[0]);
  83. }
  84. //==============================================================================
  85. void ShaderProgramUniformVariable::set(const Texture& tex) const
  86. {
  87. doSanityChecks();
  88. ANKI_ASSERT(getGlDataType() == GL_SAMPLER_2D
  89. || getGlDataType() == GL_SAMPLER_2D_SHADOW);
  90. tex.bind();
  91. glUniform1i(getLocation(), tex.getUnit());
  92. }
  93. //==============================================================================
  94. // ShaderProgram =
  95. //==============================================================================
  96. //==============================================================================
  97. const char* ShaderProgram::stdSourceCode =
  98. "#version 330 core\n"
  99. //"precision lowp float;\n"
  100. #if defined(NDEBUG)
  101. "#pragma optimize(on)\n"
  102. "#pragma debug(off)\n";
  103. #else
  104. "#pragma optimize(of)\n"
  105. "#pragma debug(on)\n";
  106. #endif
  107. const ShaderProgram* ShaderProgram::currentProgram = nullptr;
  108. //==============================================================================
  109. void ShaderProgram::create(const char* vertSource, const char* tcSource,
  110. const char* teSource, const char* geomSource, const char* fragSource,
  111. const char* transformFeedbackVaryings[])
  112. {
  113. ANKI_ASSERT(!isInitialized());
  114. // 1) create and compile the shaders
  115. //
  116. std::string preprocSource = stdSourceCode;
  117. ANKI_ASSERT(vertSource != nullptr);
  118. vertShaderGlId = createAndCompileShader(vertSource, preprocSource.c_str(),
  119. GL_VERTEX_SHADER);
  120. if(tcSource != nullptr)
  121. {
  122. tcShaderGlId = createAndCompileShader(tcSource, preprocSource.c_str(),
  123. GL_TESS_CONTROL_SHADER);
  124. }
  125. if(teSource != nullptr)
  126. {
  127. teShaderGlId = createAndCompileShader(teSource, preprocSource.c_str(),
  128. GL_TESS_EVALUATION_SHADER);
  129. }
  130. if(geomSource != nullptr)
  131. {
  132. geomShaderGlId = createAndCompileShader(geomSource,
  133. preprocSource.c_str(), GL_GEOMETRY_SHADER);
  134. }
  135. ANKI_ASSERT(fragSource != nullptr);
  136. fragShaderGlId = createAndCompileShader(fragSource, preprocSource.c_str(),
  137. GL_FRAGMENT_SHADER);
  138. // 2) create program and attach shaders
  139. glId = glCreateProgram();
  140. if(glId == 0)
  141. {
  142. throw ANKI_EXCEPTION("glCreateProgram failed");
  143. }
  144. glAttachShader(glId, vertShaderGlId);
  145. glAttachShader(glId, fragShaderGlId);
  146. if(tcSource != nullptr)
  147. {
  148. glAttachShader(glId, tcShaderGlId);
  149. }
  150. if(teSource != nullptr)
  151. {
  152. glAttachShader(glId, teShaderGlId);
  153. }
  154. if(geomSource != nullptr)
  155. {
  156. glAttachShader(glId, geomShaderGlId);
  157. }
  158. // 3) set the TRFFB varyings
  159. ANKI_ASSERT(transformFeedbackVaryings != nullptr);
  160. int count = 0;
  161. while(*transformFeedbackVaryings != nullptr)
  162. {
  163. ++count;
  164. ++transformFeedbackVaryings;
  165. }
  166. if(count)
  167. {
  168. glTransformFeedbackVaryings(glId,
  169. count,
  170. transformFeedbackVaryings,
  171. GL_SEPARATE_ATTRIBS);
  172. }
  173. // 4) link
  174. link();
  175. // init the rest
  176. getUniAndAttribVars();
  177. }
  178. //==============================================================================
  179. void ShaderProgram::destroy()
  180. {
  181. if(vertShaderGlId != 0)
  182. {
  183. glDeleteShader(vertShaderGlId);
  184. }
  185. if(tcShaderGlId != 0)
  186. {
  187. glDeleteShader(tcShaderGlId);
  188. }
  189. if(teShaderGlId != 0)
  190. {
  191. glDeleteShader(teShaderGlId);
  192. }
  193. if(geomShaderGlId != 0)
  194. {
  195. glDeleteShader(geomShaderGlId);
  196. }
  197. if(fragShaderGlId != 0)
  198. {
  199. glDeleteShader(fragShaderGlId);
  200. }
  201. glDeleteProgram(glId);
  202. }
  203. //==============================================================================
  204. GLuint ShaderProgram::createAndCompileShader(const char* sourceCode,
  205. const char* preproc, GLenum type)
  206. {
  207. uint glId = 0;
  208. const char* sourceStrs[2] = {NULL, NULL};
  209. // create the shader
  210. glId = glCreateShader(type);
  211. // attach the source
  212. sourceStrs[1] = sourceCode;
  213. sourceStrs[0] = preproc;
  214. // compile
  215. glShaderSource(glId, 2, sourceStrs, NULL);
  216. glCompileShader(glId);
  217. int success;
  218. glGetShaderiv(glId, GL_COMPILE_STATUS, &success);
  219. if(!success)
  220. {
  221. // print info log
  222. int infoLen = 0;
  223. int charsWritten = 0;
  224. std::vector<char> infoLog;
  225. glGetShaderiv(glId, GL_INFO_LOG_LENGTH, &infoLen);
  226. infoLog.resize(infoLen + 1);
  227. glGetShaderInfoLog(glId, infoLen, &charsWritten, &infoLog[0]);
  228. infoLog[charsWritten] = '\0';
  229. throw ANKI_EXCEPTION("Shader failed. Log:\n" + &infoLog[0]
  230. + "\nSource:\n" + sourceCode);
  231. }
  232. return glId;
  233. }
  234. //==============================================================================
  235. void ShaderProgram::link() const
  236. {
  237. // link
  238. glLinkProgram(glId);
  239. // check if linked correctly
  240. int success;
  241. glGetProgramiv(glId, GL_LINK_STATUS, &success);
  242. if(!success)
  243. {
  244. int info_len = 0;
  245. int charsWritten = 0;
  246. std::string infoLogTxt;
  247. glGetProgramiv(glId, GL_INFO_LOG_LENGTH, &info_len);
  248. infoLogTxt.resize(info_len + 1);
  249. glGetProgramInfoLog(glId, info_len, &charsWritten, &infoLogTxt[0]);
  250. throw ANKI_EXCEPTION("Link error log follows:\n"
  251. + infoLogTxt);
  252. }
  253. }
  254. //==============================================================================
  255. void ShaderProgram::getUniAndAttribVars()
  256. {
  257. int num;
  258. std::array<char, 256> name_;
  259. GLsizei length;
  260. GLint size;
  261. GLenum type;
  262. // attrib locations
  263. glGetProgramiv(glId, GL_ACTIVE_ATTRIBUTES, &num);
  264. for(int i = 0; i < num; i++) // loop all attributes
  265. {
  266. glGetActiveAttrib(glId, i, sizeof(name_) / sizeof(char), &length,
  267. &size, &type, &name_[0]);
  268. name_[length] = '\0';
  269. // check if its FFP location
  270. int loc = glGetAttribLocation(glId, &name_[0]);
  271. if(loc == -1) // if -1 it means that its an FFP var
  272. {
  273. ANKI_WARNING("You are using FFP vertex attributes (\""
  274. << &name_[0] << "\")");
  275. continue;
  276. }
  277. ShaderProgramAttributeVariable* var =
  278. new ShaderProgramAttributeVariable(loc, &name_[0], type,
  279. size, this);
  280. vars.push_back(var);
  281. attribs.push_back(var);
  282. nameToVar[var->getName().c_str()] = var;
  283. nameToAttribVar[var->getName().c_str()] = var;
  284. }
  285. // uni locations
  286. glGetProgramiv(glId, GL_ACTIVE_UNIFORMS, &num);
  287. for(int i = 0; i < num; i++) // loop all uniforms
  288. {
  289. glGetActiveUniform(glId, i, sizeof(name_) / sizeof(char), &length,
  290. &size, &type, &name_[0]);
  291. name_[length] = '\0';
  292. // check if its FFP location
  293. int loc = glGetUniformLocation(glId, &name_[0]);
  294. if(loc == -1) // if -1 it means that its an FFP var
  295. {
  296. ANKI_WARNING("You are using FFP vertex uniforms (\""
  297. << &name_[0] << "\")");
  298. continue;
  299. }
  300. ShaderProgramUniformVariable* var =
  301. new ShaderProgramUniformVariable(loc, &name_[0], type,
  302. size, this);
  303. vars.push_back(var);
  304. unis.push_back(var);
  305. nameToVar[var->getName().c_str()] = var;
  306. nameToUniVar[var->getName().c_str()] = var;
  307. }
  308. }
  309. //==============================================================================
  310. const ShaderProgramVariable* ShaderProgram::findVariableByName(
  311. const char* name) const
  312. {
  313. NameToVarHashMap::const_iterator it = nameToVar.find(name);
  314. if(it == nameToVar.end())
  315. {
  316. return nullptr;
  317. }
  318. return it->second;
  319. }
  320. //==============================================================================
  321. const ShaderProgramAttributeVariable*
  322. ShaderProgram::findAttributeVariableByName(const char* name) const
  323. {
  324. NameToAttribVarHashMap::const_iterator it = nameToAttribVar.find(name);
  325. if(it == nameToAttribVar.end())
  326. {
  327. return nullptr;
  328. }
  329. return it->second;
  330. }
  331. //==============================================================================
  332. const ShaderProgramUniformVariable* ShaderProgram::findUniformVariableByName(
  333. const char* name) const
  334. {
  335. NameToUniVarHashMap::const_iterator it = nameToUniVar.find(name);
  336. if(it == nameToUniVar.end())
  337. {
  338. return nullptr;
  339. }
  340. return it->second;
  341. }
  342. //==============================================================================
  343. std::ostream& operator<<(std::ostream& s, const ShaderProgram& x)
  344. {
  345. s << "ShaderProgram\n";
  346. s << "Variables:\n";
  347. for(const ShaderProgramVariable& var : x.vars)
  348. {
  349. s << var.getName() << " " << var.getLocation() << " "
  350. << (var.getType() == ShaderProgramVariable::SPVT_ATTRIBUTE
  351. ? "[A]" : "[U]") << '\n';
  352. }
  353. return s;
  354. }
  355. } // end namespace