Shader.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. /**
  2. * Copyright (c) 2006-2013 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "common/config.h"
  21. #include "Shader.h"
  22. #include "Graphics.h"
  23. #include <algorithm>
  24. namespace love
  25. {
  26. namespace graphics
  27. {
  28. namespace opengl
  29. {
  30. namespace
  31. {
  32. // temporarily attaches a shader program (for setting uniforms, etc)
  33. // reattaches the originally active program when destroyed
  34. struct TemporaryAttacher
  35. {
  36. TemporaryAttacher(Shader *shader)
  37. : curShader(shader)
  38. , prevShader(Shader::current)
  39. {
  40. curShader->attach(true);
  41. }
  42. ~TemporaryAttacher()
  43. {
  44. if (prevShader != NULL)
  45. prevShader->attach();
  46. else
  47. curShader->detach();
  48. }
  49. Shader *curShader;
  50. Shader *prevShader;
  51. };
  52. } // anonymous namespace
  53. Shader *Shader::current = NULL;
  54. GLint Shader::maxTextureUnits = 0;
  55. std::vector<int> Shader::textureCounters;
  56. Shader::Shader(const ShaderSources &sources)
  57. : shaderSources(sources)
  58. , program(0)
  59. {
  60. if (shaderSources.empty())
  61. throw love::Exception("Cannot create shader: no source code!");
  62. if (maxTextureUnits <= 0)
  63. {
  64. GLint maxtexunits;
  65. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxtexunits);
  66. maxTextureUnits = std::max(maxtexunits - 1, 0);
  67. }
  68. // initialize global texture id counters if needed
  69. if (textureCounters.size() < (size_t) maxTextureUnits)
  70. textureCounters.resize(maxTextureUnits, 0);
  71. // load shader source and create program object
  72. loadVolatile();
  73. }
  74. Shader::~Shader()
  75. {
  76. if (current == this)
  77. detach();
  78. unloadVolatile();
  79. }
  80. GLuint Shader::compileCode(ShaderType type, const std::string &code)
  81. {
  82. GLenum glshadertype;
  83. const char *typestr;
  84. if (!typeNames.find(type, typestr))
  85. typestr = "";
  86. switch (type)
  87. {
  88. case TYPE_VERTEX:
  89. glshadertype = GL_VERTEX_SHADER;
  90. break;
  91. case TYPE_PIXEL:
  92. glshadertype = GL_FRAGMENT_SHADER;
  93. break;
  94. default:
  95. throw love::Exception("Cannot create shader object: unknown shader type.");
  96. break;
  97. }
  98. // clear existing errors
  99. while (glGetError() != GL_NO_ERROR);
  100. GLuint shaderid = glCreateShader(glshadertype);
  101. if (shaderid == 0) // oh no!
  102. {
  103. GLenum err = glGetError();
  104. if (err == GL_INVALID_ENUM) // invalid or unsupported shader type
  105. throw love::Exception("Cannot create %s shader object: %s shaders not supported.", typestr, typestr);
  106. else // other errors should only happen between glBegin() and glEnd()
  107. throw love::Exception("Cannot create %s shader object.", typestr);
  108. }
  109. const char *src = code.c_str();
  110. size_t srclen = code.length();
  111. glShaderSource(shaderid, 1, (const GLchar **)&src, (GLint *)&srclen);
  112. glCompileShader(shaderid);
  113. // Get any warnings the shader compiler may have produced
  114. GLint infologlen;
  115. glGetShaderiv(shaderid, GL_INFO_LOG_LENGTH, &infologlen);
  116. GLchar *infolog = new GLchar[infologlen + 1];
  117. glGetShaderInfoLog(shaderid, infologlen, NULL, infolog);
  118. // Save any warnings for later querying
  119. if (infologlen > 0)
  120. shaderWarnings[type] = infolog;
  121. delete[] infolog;
  122. GLint status;
  123. glGetShaderiv(shaderid, GL_COMPILE_STATUS, &status);
  124. if (status == GL_FALSE)
  125. {
  126. throw love::Exception("Cannot compile %s shader code:\n%s",
  127. typestr, shaderWarnings[type].c_str());
  128. }
  129. return shaderid;
  130. }
  131. void Shader::createProgram(const std::vector<GLuint> &shaderids)
  132. {
  133. program = glCreateProgram();
  134. if (program == 0) // should only fail when called between glBegin() and glEnd()
  135. throw love::Exception("Cannot create shader program object.");
  136. std::vector<GLuint>::const_iterator it;
  137. for (it = shaderids.begin(); it != shaderids.end(); ++it)
  138. glAttachShader(program, *it);
  139. glLinkProgram(program);
  140. for (it = shaderids.begin(); it != shaderids.end(); ++it)
  141. glDeleteShader(*it); // flag shaders for auto-deletion when program object is deleted
  142. GLint status;
  143. glGetProgramiv(program, GL_LINK_STATUS, &status);
  144. if (status == GL_FALSE)
  145. {
  146. std::string warnings = getProgramWarnings();
  147. glDeleteProgram(program);
  148. throw love::Exception("Cannot link shader program object:\n%s", warnings.c_str());
  149. }
  150. }
  151. void Shader::mapActiveUniforms()
  152. {
  153. uniforms.clear();
  154. GLint numuniforms;
  155. glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &numuniforms);
  156. GLsizei bufsize;
  157. glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, (GLint *) &bufsize);
  158. for (int i = 0; i < numuniforms; i++)
  159. {
  160. GLchar *cname = new GLchar[bufsize];
  161. GLsizei namelength;
  162. Uniform u;
  163. glGetActiveUniform(program, (GLuint) i, bufsize, &namelength, &u.count, &u.type, cname);
  164. u.name = std::string(cname, (size_t) namelength);
  165. u.location = glGetUniformLocation(program, u.name.c_str());
  166. u.baseType = getUniformBaseType(u.type);
  167. delete[] cname;
  168. // glGetActiveUniform appends "[0]" to the end of array uniform names...
  169. if (u.name.find("[0]") == u.name.length() - 3)
  170. u.name.erase(u.name.length() - 3);
  171. if (u.location != -1)
  172. uniforms[u.name] = u;
  173. }
  174. }
  175. bool Shader::loadVolatile()
  176. {
  177. // zero out active texture list
  178. activeTextureUnits.clear();
  179. activeTextureUnits.insert(activeTextureUnits.begin(), maxTextureUnits, 0);
  180. std::vector<GLuint> shaderids;
  181. ShaderSources::const_iterator source;
  182. for (source = shaderSources.begin(); source != shaderSources.end(); ++source)
  183. {
  184. GLuint shaderid = compileCode(source->first, source->second);
  185. shaderids.push_back(shaderid);
  186. }
  187. if (shaderids.empty())
  188. throw love::Exception("Cannot create shader: no valid source code!");
  189. createProgram(shaderids);
  190. mapActiveUniforms();
  191. if (current == this)
  192. {
  193. current = NULL; // make sure glUseProgram gets called
  194. attach();
  195. }
  196. return true;
  197. }
  198. void Shader::unloadVolatile()
  199. {
  200. if (current == this)
  201. glUseProgram(0);
  202. if (program != 0)
  203. glDeleteProgram(program);
  204. program = 0;
  205. // decrement global texture id counters for texture units which had textures bound from this shader
  206. for (size_t i = 0; i < activeTextureUnits.size(); ++i)
  207. {
  208. if (activeTextureUnits[i] > 0)
  209. textureCounters[i] = std::max(textureCounters[i] - 1, 0);
  210. }
  211. // active texture list is probably invalid, clear it
  212. activeTextureUnits.clear();
  213. activeTextureUnits.insert(activeTextureUnits.begin(), maxTextureUnits, 0);
  214. // same with uniform location list
  215. uniforms.clear();
  216. shaderWarnings.clear();
  217. }
  218. std::string Shader::getProgramWarnings() const
  219. {
  220. GLint strlen, nullpos;
  221. glGetProgramiv(program, GL_INFO_LOG_LENGTH, &strlen);
  222. char *tempstr = new char[strlen+1];
  223. // be extra sure that the error string will be 0-terminated
  224. memset(tempstr, '\0', strlen+1);
  225. glGetProgramInfoLog(program, strlen, &nullpos, tempstr);
  226. tempstr[nullpos] = '\0';
  227. std::string warnings(tempstr);
  228. delete[] tempstr;
  229. return warnings;
  230. }
  231. std::string Shader::getWarnings() const
  232. {
  233. std::string warnings;
  234. const char *typestr;
  235. // Get the individual shader stage warnings
  236. std::map<ShaderType, std::string>::const_iterator it;
  237. for (it = shaderWarnings.begin(); it != shaderWarnings.end(); ++it)
  238. {
  239. if (typeNames.find(it->first, typestr))
  240. warnings += std::string(typestr) + std::string(" shader:\n") + it->second;
  241. }
  242. warnings += getProgramWarnings();
  243. return warnings;
  244. }
  245. void Shader::attach(bool temporary)
  246. {
  247. if (current != this)
  248. glUseProgram(program);
  249. current = this;
  250. if (!temporary)
  251. {
  252. // make sure all sent textures are properly bound to their respective texture units
  253. // note: list potentially contains texture ids of deleted/invalid textures!
  254. for (size_t i = 0; i < activeTextureUnits.size(); ++i)
  255. {
  256. if (activeTextureUnits[i] > 0)
  257. gl.bindTextureToUnit(activeTextureUnits[i], i + 1, false);
  258. }
  259. gl.setActiveTextureUnit(0);
  260. }
  261. }
  262. void Shader::detach()
  263. {
  264. if (current != NULL)
  265. glUseProgram(0);
  266. current = NULL;
  267. }
  268. const Shader::Uniform &Shader::getUniform(const std::string &name) const
  269. {
  270. std::map<std::string, Uniform>::const_iterator it = uniforms.find(name);
  271. if (it == uniforms.end())
  272. throw love::Exception("Variable '%s' does not exist.\n"
  273. "A common error is to define but not use the variable.", name.c_str());
  274. return it->second;
  275. }
  276. int Shader::getUniformTypeSize(GLenum type) const
  277. {
  278. switch (type)
  279. {
  280. case GL_INT:
  281. case GL_FLOAT:
  282. case GL_BOOL:
  283. case GL_SAMPLER_1D:
  284. case GL_SAMPLER_2D:
  285. case GL_SAMPLER_3D:
  286. return 1;
  287. case GL_INT_VEC2:
  288. case GL_FLOAT_VEC2:
  289. case GL_FLOAT_MAT2:
  290. case GL_BOOL_VEC2:
  291. return 2;
  292. case GL_INT_VEC3:
  293. case GL_FLOAT_VEC3:
  294. case GL_FLOAT_MAT3:
  295. case GL_BOOL_VEC3:
  296. return 3;
  297. case GL_INT_VEC4:
  298. case GL_FLOAT_VEC4:
  299. case GL_FLOAT_MAT4:
  300. case GL_BOOL_VEC4:
  301. return 4;
  302. default:
  303. break;
  304. }
  305. return 1;
  306. }
  307. Shader::UniformType Shader::getUniformBaseType(GLenum type) const
  308. {
  309. switch (type)
  310. {
  311. case GL_INT:
  312. case GL_INT_VEC2:
  313. case GL_INT_VEC3:
  314. case GL_INT_VEC4:
  315. return UNIFORM_INT;
  316. case GL_FLOAT:
  317. case GL_FLOAT_VEC2:
  318. case GL_FLOAT_VEC3:
  319. case GL_FLOAT_VEC4:
  320. case GL_FLOAT_MAT2:
  321. case GL_FLOAT_MAT3:
  322. case GL_FLOAT_MAT4:
  323. return UNIFORM_FLOAT;
  324. case GL_BOOL:
  325. case GL_BOOL_VEC2:
  326. case GL_BOOL_VEC3:
  327. case GL_BOOL_VEC4:
  328. return UNIFORM_BOOL;
  329. case GL_SAMPLER_1D:
  330. case GL_SAMPLER_2D:
  331. case GL_SAMPLER_3D:
  332. return UNIFORM_SAMPLER;
  333. default:
  334. break;
  335. }
  336. return UNIFORM_UNKNOWN;
  337. }
  338. void Shader::checkSetUniformError(const Uniform &u, int size, int count, UniformType sendtype) const
  339. {
  340. if (!program)
  341. throw love::Exception("No active shader program.");
  342. int realsize = getUniformTypeSize(u.type);
  343. if (size != realsize)
  344. throw love::Exception("Value size of %d does not match variable size of %d.", size, realsize);
  345. if ((u.count == 1 && count > 1) || count < 0)
  346. throw love::Exception("Invalid number of values (expected %d, got %d).", u.count, count);
  347. if (u.baseType == UNIFORM_SAMPLER && sendtype != u.baseType)
  348. throw love::Exception("Cannot send a value of this type to an Image variable.");
  349. if ((sendtype == UNIFORM_FLOAT && u.baseType == UNIFORM_INT) || (sendtype == UNIFORM_INT && u.baseType == UNIFORM_FLOAT))
  350. throw love::Exception("Cannot convert between float and int.");
  351. }
  352. void Shader::sendInt(const std::string &name, int size, const GLint *vec, int count)
  353. {
  354. TemporaryAttacher attacher(this);
  355. const Uniform &u = getUniform(name);
  356. checkSetUniformError(u, size, count, UNIFORM_INT);
  357. switch (size)
  358. {
  359. case 4:
  360. glUniform4iv(u.location, count, vec);
  361. break;
  362. case 3:
  363. glUniform3iv(u.location, count, vec);
  364. break;
  365. case 2:
  366. glUniform2iv(u.location, count, vec);
  367. break;
  368. case 1:
  369. default:
  370. glUniform1iv(u.location, count, vec);
  371. break;
  372. }
  373. }
  374. void Shader::sendFloat(const std::string &name, int size, const GLfloat *vec, int count)
  375. {
  376. TemporaryAttacher attacher(this);
  377. const Uniform &u = getUniform(name);
  378. checkSetUniformError(u, size, count, UNIFORM_FLOAT);
  379. switch (size)
  380. {
  381. case 4:
  382. glUniform4fv(u.location, count, vec);
  383. break;
  384. case 3:
  385. glUniform3fv(u.location, count, vec);
  386. break;
  387. case 2:
  388. glUniform2fv(u.location, count, vec);
  389. break;
  390. case 1:
  391. default:
  392. glUniform1fv(u.location, count, vec);
  393. break;
  394. }
  395. }
  396. void Shader::sendMatrix(const std::string &name, int size, const GLfloat *m, int count)
  397. {
  398. TemporaryAttacher attacher(this);
  399. if (size < 2 || size > 4)
  400. {
  401. throw love::Exception("Invalid matrix size: %dx%d "
  402. "(can only set 2x2, 3x3 or 4x4 matrices).", size,size);
  403. }
  404. const Uniform &u = getUniform(name);
  405. checkSetUniformError(u, size, count, UNIFORM_FLOAT);
  406. switch (size)
  407. {
  408. case 4:
  409. glUniformMatrix4fv(u.location, count, GL_FALSE, m);
  410. break;
  411. case 3:
  412. glUniformMatrix3fv(u.location, count, GL_FALSE, m);
  413. break;
  414. case 2:
  415. default:
  416. glUniformMatrix2fv(u.location, count, GL_FALSE, m);
  417. break;
  418. }
  419. }
  420. void Shader::sendTexture(const std::string &name, GLuint texture)
  421. {
  422. TemporaryAttacher attacher(this);
  423. int textureunit = getTextureUnit(name);
  424. const Uniform &u = getUniform(name);
  425. checkSetUniformError(u, 1, 1, UNIFORM_SAMPLER);
  426. // bind texture to assigned texture unit and send uniform to shader program
  427. gl.bindTextureToUnit(texture, textureunit, false);
  428. glUniform1i(u.location, textureunit);
  429. // reset texture unit
  430. gl.setActiveTextureUnit(0);
  431. // increment global shader texture id counter for this texture unit, if we haven't already
  432. if (activeTextureUnits[textureunit-1] == 0)
  433. ++textureCounters[textureunit-1];
  434. // store texture id so it can be re-bound to the proper texture unit when necessary
  435. activeTextureUnits[textureunit-1] = texture;
  436. }
  437. void Shader::sendImage(const std::string &name, const Image &image)
  438. {
  439. sendTexture(name, image.getTextureName());
  440. }
  441. void Shader::sendCanvas(const std::string &name, const Canvas &canvas)
  442. {
  443. sendTexture(name, canvas.getTextureName());
  444. }
  445. int Shader::getTextureUnit(const std::string &name)
  446. {
  447. std::map<std::string, GLint>::const_iterator it = textureUnitPool.find(name);
  448. if (it != textureUnitPool.end())
  449. return it->second;
  450. int textureunit = 1;
  451. // prefer texture units which are unused by all other shaders
  452. std::vector<int>::iterator nextfreeunit = std::find(textureCounters.begin(), textureCounters.end(), 0);
  453. if (nextfreeunit != textureCounters.end())
  454. textureunit = std::distance(textureCounters.begin(), nextfreeunit) + 1; // we don't want to use unit 0
  455. else
  456. {
  457. // no completely unused texture units exist, try to use next free slot in our own list
  458. std::vector<GLuint>::iterator nexttexunit = std::find(activeTextureUnits.begin(), activeTextureUnits.end(), 0);
  459. if (nexttexunit == activeTextureUnits.end())
  460. throw love::Exception("No more texture units available for shader.");
  461. textureunit = std::distance(activeTextureUnits.begin(), nexttexunit) + 1; // we don't want to use unit 0
  462. }
  463. textureUnitPool[name] = textureunit;
  464. return textureunit;
  465. }
  466. std::string Shader::getGLSLVersion()
  467. {
  468. // GL_SHADING_LANGUAGE_VERSION may not be available in OpenGL < 2.0.
  469. const char *tmp = (const char *) glGetString(GL_SHADING_LANGUAGE_VERSION);
  470. if (tmp == NULL)
  471. return "0.0";
  472. // the version string always begins with a version number of the format
  473. // major_number.minor_number
  474. // or
  475. // major_number.minor_number.release_number
  476. // we can keep release_number, since it does not affect the check below.
  477. std::string versionstring(tmp);
  478. size_t minorendpos = versionstring.find(' ');
  479. return versionstring.substr(0, minorendpos);
  480. }
  481. bool Shader::isSupported()
  482. {
  483. return GLEE_VERSION_2_0 && getGLSLVersion() >= "1.2";
  484. }
  485. StringMap<Shader::ShaderType, Shader::TYPE_MAX_ENUM>::Entry Shader::typeNameEntries[] =
  486. {
  487. {"vertex", Shader::TYPE_VERTEX},
  488. {"pixel", Shader::TYPE_PIXEL},
  489. };
  490. StringMap<Shader::ShaderType, Shader::TYPE_MAX_ENUM> Shader::typeNames(Shader::typeNameEntries, sizeof(Shader::typeNameEntries));
  491. } // opengl
  492. } // graphics
  493. } // love