ShaderEffect.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /**
  2. * Copyright (c) 2006-2012 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 "ShaderEffect.h"
  21. #include "Graphics.h"
  22. namespace love
  23. {
  24. namespace graphics
  25. {
  26. namespace opengl
  27. {
  28. namespace
  29. {
  30. // temporarily attaches a shader program (for setting uniforms, etc)
  31. // reattaches the originally active program when destroyed
  32. struct TemporaryAttacher
  33. {
  34. TemporaryAttacher(ShaderEffect *sp)
  35. : cureffect(sp)
  36. , preveffect(ShaderEffect::current)
  37. {
  38. cureffect->attach(true);
  39. }
  40. ~TemporaryAttacher()
  41. {
  42. if (preveffect != NULL)
  43. preveffect->attach();
  44. else
  45. ShaderEffect::detach();
  46. }
  47. ShaderEffect *cureffect;
  48. ShaderEffect *preveffect;
  49. };
  50. } // anonymous namespace
  51. ShaderEffect *ShaderEffect::current = NULL;
  52. GLint ShaderEffect::_maxtextureunits = 0;
  53. std::vector<int> ShaderEffect::_texturecounters;
  54. ShaderEffect::ShaderEffect(const std::vector<ShaderSource> &shadersources)
  55. : _shadersources(shadersources)
  56. , _program(0)
  57. {
  58. if (shadersources.size() == 0)
  59. throw love::Exception("Cannot create shader effect: no source code!");
  60. GLint maxtextureunits;
  61. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxtextureunits);
  62. _maxtextureunits = std::max(maxtextureunits - 1, 0);
  63. // initialize global texture id counters if needed
  64. if (_texturecounters.size() < (size_t) _maxtextureunits)
  65. _texturecounters.resize(_maxtextureunits, 0);
  66. // load shader source and create program object
  67. loadVolatile();
  68. }
  69. ShaderEffect::~ShaderEffect()
  70. {
  71. if (current == this)
  72. detach();
  73. unloadVolatile();
  74. }
  75. GLuint ShaderEffect::createShader(const ShaderSource &source)
  76. {
  77. GLenum shadertype;
  78. const char *shadertypename = NULL;
  79. switch (source.type)
  80. {
  81. case TYPE_VERTEX:
  82. shadertype = GL_VERTEX_SHADER;
  83. shadertypename = "vertex";
  84. break;
  85. case TYPE_TESSCONTROL:
  86. shadertype = GL_TESS_CONTROL_SHADER;
  87. shadertypename = "tesselation control";
  88. break;
  89. case TYPE_TESSEVAL:
  90. shadertype = GL_TESS_EVALUATION_SHADER;
  91. shadertypename = "tesselation evaluation";
  92. break;
  93. case TYPE_GEOMETRY:
  94. shadertype = GL_GEOMETRY_SHADER;
  95. shadertypename = "geometry";
  96. break;
  97. case TYPE_FRAGMENT:
  98. shadertype = GL_FRAGMENT_SHADER;
  99. shadertypename = "fragment";
  100. break;
  101. default:
  102. throw love::Exception("Cannot create shader object: unknown shader type.");
  103. break;
  104. }
  105. // clear existing errors
  106. while (glGetError() != GL_NO_ERROR);
  107. GLuint shaderid = glCreateShader(shadertype);
  108. if (shaderid == 0) // oh no!
  109. {
  110. GLenum err = glGetError();
  111. if (err == GL_INVALID_ENUM) // invalid or unsupported shader type
  112. throw love::Exception("Cannot create %s shader object: %s shaders not supported.", shadertypename, shadertypename);
  113. else // other errors should only happen between glBegin() and glEnd()
  114. throw love::Exception("Cannot create %s shader object.", shadertypename);
  115. }
  116. const char *src = source.code.c_str();
  117. size_t srclen = source.code.length();
  118. glShaderSource(shaderid, 1, (const GLchar **)&src, (GLint *)&srclen);
  119. glCompileShader(shaderid);
  120. GLint compile_status;
  121. glGetShaderiv(shaderid, GL_COMPILE_STATUS, &compile_status);
  122. if (compile_status == GL_FALSE)
  123. {
  124. GLint infologlen;
  125. glGetShaderiv(shaderid, GL_INFO_LOG_LENGTH, &infologlen);
  126. GLchar *errorlog = new GLchar[infologlen + 1];
  127. glGetShaderInfoLog(shaderid, infologlen, NULL, errorlog);
  128. std::string tmp(errorlog);
  129. delete[] errorlog;
  130. glDeleteShader(shaderid);
  131. throw love::Exception("Cannot compile %s shader:\n%s", shadertypename, tmp.c_str());
  132. }
  133. return shaderid;
  134. }
  135. void ShaderEffect::createProgram(const std::vector<GLuint> &shaderids)
  136. {
  137. _program = glCreateProgram();
  138. if (_program == 0) // should only fail when called between glBegin() and glEnd()
  139. throw love::Exception("Cannot create shader program object.");
  140. std::vector<GLuint>::const_iterator it;
  141. for (it = shaderids.begin(); it != shaderids.end(); ++it)
  142. glAttachShader(_program, *it);
  143. glLinkProgram(_program);
  144. for (it = shaderids.begin(); it != shaderids.end(); ++it)
  145. glDeleteShader(*it); // flag shaders for auto-deletion when program object is deleted
  146. GLint link_ok;
  147. glGetProgramiv(_program, GL_LINK_STATUS, &link_ok);
  148. if (link_ok == GL_FALSE)
  149. {
  150. const std::string warnings = getWarnings();
  151. glDeleteProgram(_program);
  152. throw love::Exception("Cannot link shader program object:\n%s", warnings.c_str());
  153. }
  154. }
  155. bool ShaderEffect::loadVolatile()
  156. {
  157. // zero out active texture list
  158. _activetextureunits.clear();
  159. _activetextureunits.insert(_activetextureunits.begin(), _maxtextureunits, 0);
  160. std::vector<GLuint> shaderids;
  161. std::vector<ShaderSource>::const_iterator source;
  162. for (source = _shadersources.begin(); source != _shadersources.end(); ++source)
  163. shaderids.push_back(createShader(*source));
  164. if (shaderids.size() == 0)
  165. throw love::Exception("Cannot create shader effect: no valid source code!");
  166. createProgram(shaderids);
  167. if (current == this)
  168. {
  169. current = NULL; // make sure glUseProgram gets called
  170. attach();
  171. }
  172. return true;
  173. }
  174. void ShaderEffect::unloadVolatile()
  175. {
  176. if (current == this)
  177. glUseProgram(0);
  178. if (_program != 0)
  179. glDeleteProgram(_program);
  180. _program = 0;
  181. // decrement global texture id counters for texture units which had textures bound from this shader
  182. for (size_t i = 0; i < _activetextureunits.size(); ++i)
  183. {
  184. if (_activetextureunits[i] == 0)
  185. continue;
  186. _texturecounters[i] = std::max(_texturecounters[i] - 1, 0);
  187. }
  188. // active texture list is probably invalid, clear it
  189. _activetextureunits.clear();
  190. _activetextureunits.insert(_activetextureunits.begin(), _maxtextureunits, 0);
  191. // same with uniform location list
  192. _uniforms.clear();
  193. }
  194. std::string ShaderEffect::getWarnings() const
  195. {
  196. GLint strlen, nullpos;
  197. glGetProgramiv(_program, GL_INFO_LOG_LENGTH, &strlen);
  198. char *temp_str = new char[strlen+1];
  199. // be extra sure that the error string will be 0-terminated
  200. memset(temp_str, '\0', strlen+1);
  201. glGetProgramInfoLog(_program, strlen, &nullpos, temp_str);
  202. temp_str[nullpos] = '\0';
  203. std::string warnings(temp_str);
  204. delete[] temp_str;
  205. return warnings;
  206. }
  207. void ShaderEffect::attach(bool temporary)
  208. {
  209. if (current != this)
  210. glUseProgram(_program);
  211. current = this;
  212. if (!temporary)
  213. {
  214. // make sure all sent textures are properly bound to their respective texture units
  215. // note: list potentially contains texture ids of deleted/invalid textures!
  216. for (size_t i = 0; i < _activetextureunits.size(); ++i)
  217. {
  218. if (_activetextureunits[i] == 0)
  219. continue;
  220. bindTextureToUnit(_activetextureunits[i], GL_TEXTURE0 + i + 1, false);
  221. }
  222. setActiveTextureUnit(GL_TEXTURE0);
  223. }
  224. }
  225. void ShaderEffect::detach()
  226. {
  227. if (current != NULL)
  228. glUseProgram(0);
  229. current = NULL;
  230. }
  231. void ShaderEffect::sendFloat(const std::string &name, int size, const GLfloat *vec, int count)
  232. {
  233. TemporaryAttacher attacher(this);
  234. GLint location = getUniformLocation(name);
  235. if (size < 1 || size > 4)
  236. throw love::Exception("Invalid variable size: %d (expected 1-4).", size);
  237. switch (size)
  238. {
  239. case 4:
  240. glUniform4fv(location, count, vec);
  241. break;
  242. case 3:
  243. glUniform3fv(location, count, vec);
  244. break;
  245. case 2:
  246. glUniform2fv(location, count, vec);
  247. break;
  248. case 1:
  249. default:
  250. glUniform1fv(location, count, vec);
  251. break;
  252. }
  253. // throw error if needed
  254. checkSetUniformError();
  255. }
  256. void ShaderEffect::sendMatrix(const std::string &name, int size, const GLfloat *m, int count)
  257. {
  258. TemporaryAttacher attacher(this);
  259. GLint location = getUniformLocation(name);
  260. if (size < 2 || size > 4)
  261. {
  262. throw love::Exception("Invalid matrix size: %dx%d "
  263. "(can only set 2x2, 3x3 or 4x4 matrices).", size,size);
  264. }
  265. switch (size)
  266. {
  267. case 4:
  268. glUniformMatrix4fv(location, count, GL_FALSE, m);
  269. break;
  270. case 3:
  271. glUniformMatrix3fv(location, count, GL_FALSE, m);
  272. break;
  273. case 2:
  274. default:
  275. glUniformMatrix2fv(location, count, GL_FALSE, m);
  276. break;
  277. }
  278. // throw error if needed
  279. checkSetUniformError();
  280. }
  281. void ShaderEffect::sendTexture(const std::string &name, GLuint texture)
  282. {
  283. TemporaryAttacher attacher(this);
  284. GLint location = getUniformLocation(name);
  285. GLint texture_unit = getTextureUnit(name);
  286. // bind texture to assigned texture unit and send uniform to bound shader program
  287. bindTextureToUnit(texture, GL_TEXTURE0 + texture_unit, false);
  288. glUniform1i(location, texture_unit);
  289. // reset texture unit
  290. setActiveTextureUnit(GL_TEXTURE0);
  291. // increment global shader texture id counter for this texture unit, if we haven't already
  292. if (_activetextureunits[texture_unit-1] == 0)
  293. ++_texturecounters[texture_unit-1];
  294. // store texture id so it can be re-bound to the proper texture unit when necessary
  295. _activetextureunits[texture_unit-1] = texture;
  296. // throw error if needed
  297. checkSetUniformError();
  298. }
  299. void ShaderEffect::sendImage(const std::string &name, const Image &image)
  300. {
  301. sendTexture(name, image.getTextureName());
  302. }
  303. void ShaderEffect::sendCanvas(const std::string &name, const Canvas &canvas)
  304. {
  305. sendTexture(name, canvas.getTextureName());
  306. }
  307. GLint ShaderEffect::getUniformLocation(const std::string &name)
  308. {
  309. std::map<std::string, GLint>::const_iterator it = _uniforms.find(name);
  310. if (it != _uniforms.end())
  311. return it->second;
  312. GLint location = glGetUniformLocation(_program, name.c_str());
  313. if (location == -1)
  314. {
  315. throw love::Exception(
  316. "Cannot get location of shader variable `%s'.\n"
  317. "A common error is to define but not use the variable.", name.c_str());
  318. }
  319. _uniforms[name] = location;
  320. return location;
  321. }
  322. GLint ShaderEffect::getTextureUnit(const std::string &name)
  323. {
  324. std::map<std::string, GLint>::const_iterator it = _textureunitpool.find(name);
  325. if (it != _textureunitpool.end())
  326. return it->second;
  327. int nextunitindex = 1;
  328. // prefer texture units which are unused by all other shaders
  329. std::vector<int>::iterator nextfreeunit = std::find(_texturecounters.begin(), _texturecounters.end(), 0);
  330. if (nextfreeunit != _texturecounters.end())
  331. nextunitindex = std::distance(_texturecounters.begin(), nextfreeunit) + 1; // we don't want to use unit 0
  332. else
  333. {
  334. // no completely unused texture units exist, try to use next free slot in our own list
  335. std::vector<GLuint>::iterator nexttexunit = std::find(_activetextureunits.begin(), _activetextureunits.end(), 0);
  336. if (nexttexunit == _activetextureunits.end())
  337. throw love::Exception("No more texture units available for shader.");
  338. nextunitindex = std::distance(_activetextureunits.begin(), nexttexunit) + 1; // we don't want to use unit 0
  339. }
  340. _textureunitpool[name] = nextunitindex;
  341. return nextunitindex;
  342. }
  343. void ShaderEffect::checkSetUniformError()
  344. {
  345. GLenum error_code = glGetError();
  346. if (GL_INVALID_OPERATION == error_code)
  347. {
  348. throw love::Exception(
  349. "Invalid operation:\n"
  350. "- Trying to send the wrong value type to shader variable, or\n"
  351. "- Trying to send array values with wrong dimension, or\n"
  352. "- Invalid variable name.");
  353. }
  354. }
  355. std::string ShaderEffect::getGLSLVersion()
  356. {
  357. // GL_SHADING_LANGUAGE_VERSION may not be available in OpenGL < 2.0.
  358. const char *tmp = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
  359. if (NULL == tmp)
  360. return "0.0";
  361. // the version string always begins with a version number of the format
  362. // major_number.minor_number
  363. // or
  364. // major_number.minor_number.release_number
  365. // we can keep release_number, since it does not affect the check below.
  366. std::string versionString(tmp);
  367. size_t minorEndPos = versionString.find(' ');
  368. return versionString.substr(0, minorEndPos);
  369. }
  370. bool ShaderEffect::isSupported()
  371. {
  372. return GLEE_VERSION_2_0 && getGLSLVersion() >= "1.2";
  373. }
  374. } // opengl
  375. } // graphics
  376. } // love