ShaderEffect.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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
  23. {
  24. // temporarily attaches a shader program (for setting uniforms, etc)
  25. // reattaches the originally active program when destroyed
  26. struct TemporaryAttacher
  27. {
  28. TemporaryAttacher(love::graphics::opengl::ShaderEffect *sp)
  29. : cureffect(sp)
  30. , preveffect(love::graphics::opengl::ShaderEffect::current)
  31. {
  32. cureffect->attach(true);
  33. }
  34. ~TemporaryAttacher()
  35. {
  36. if (preveffect != NULL)
  37. preveffect->attach();
  38. else
  39. love::graphics::opengl::ShaderEffect::detach();
  40. }
  41. love::graphics::opengl::ShaderEffect *cureffect;
  42. love::graphics::opengl::ShaderEffect *preveffect;
  43. };
  44. } // anonymous namespace
  45. namespace love
  46. {
  47. namespace graphics
  48. {
  49. namespace opengl
  50. {
  51. ShaderEffect *ShaderEffect::current = NULL;
  52. GLint ShaderEffect::_max_texture_units = 0;
  53. std::vector<int> ShaderEffect::_texture_id_counters;
  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. _max_texture_units = std::max(maxtextureunits - 1, 0);
  63. // initialize global texture id counters if needed
  64. if (_texture_id_counters.size() < (size_t) _max_texture_units)
  65. _texture_id_counters.resize(_max_texture_units, 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_OPERATION) // should only happen between glBegin() and glEnd()
  112. throw love::Exception("Cannot create %s shader object.", shadertypename);
  113. else if (err == GL_INVALID_ENUM) // invalid or unsupported shader type
  114. throw love::Exception("Cannot create %s shader object: %s shaders not supported.", shadertypename, 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 texture id list
  158. _texture_id_list.clear();
  159. _texture_id_list.insert(_texture_id_list.begin(), _max_texture_units, 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 < _texture_id_list.size(); ++i)
  183. {
  184. if (_texture_id_list[i] == 0)
  185. continue;
  186. _texture_id_counters[i] = std::max(_texture_id_counters[i] - 1, 0);
  187. }
  188. // texture list is probably invalid, clear it
  189. _texture_id_list.clear();
  190. _texture_id_list.insert(_texture_id_list.begin(), _max_texture_units, 0);
  191. // same with uniform location list
  192. _uniforms.clear();
  193. }
  194. std::string ShaderEffect::getGLSLVersion()
  195. {
  196. // GL_SHADING_LANGUAGE_VERSION may not be available in OpenGL < 2.0.
  197. const char *tmp = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
  198. if (NULL == tmp)
  199. return "0.0";
  200. // the version string always begins with a version number of the format
  201. // major_number.minor_number
  202. // or
  203. // major_number.minor_number.release_number
  204. // we can keep release_number, since it does not affect the check below.
  205. std::string versionString(tmp);
  206. size_t minorEndPos = versionString.find(' ');
  207. return versionString.substr(0, minorEndPos);
  208. }
  209. bool ShaderEffect::isSupported()
  210. {
  211. return GLEE_VERSION_2_0 && getGLSLVersion() >= "1.2";
  212. }
  213. std::string ShaderEffect::getWarnings() const
  214. {
  215. GLint strlen, nullpos;
  216. glGetProgramiv(_program, GL_INFO_LOG_LENGTH, &strlen);
  217. char *temp_str = new char[strlen+1];
  218. // be extra sure that the error string will be 0-terminated
  219. memset(temp_str, '\0', strlen+1);
  220. glGetProgramInfoLog(_program, strlen, &nullpos, temp_str);
  221. temp_str[nullpos] = '\0';
  222. std::string warnings(temp_str);
  223. delete[] temp_str;
  224. return warnings;
  225. }
  226. void ShaderEffect::attach(bool temporary)
  227. {
  228. if (current != this)
  229. glUseProgram(_program);
  230. current = this;
  231. if (!temporary)
  232. {
  233. // make sure all sent textures are properly bound to their respective texture units
  234. // note: list potentially contains texture ids of deleted/invalid textures!
  235. for (size_t i = 0; i < _texture_id_list.size(); ++i)
  236. {
  237. if (_texture_id_list[i] == 0)
  238. continue;
  239. bindTextureToUnit(_texture_id_list[i], GL_TEXTURE0 + i + 1, false);
  240. }
  241. setActiveTextureUnit(GL_TEXTURE0);
  242. }
  243. }
  244. void ShaderEffect::detach()
  245. {
  246. if (current != NULL)
  247. glUseProgram(0);
  248. current = NULL;
  249. }
  250. void ShaderEffect::sendFloat(const std::string &name, int size, const GLfloat *vec, int count)
  251. {
  252. TemporaryAttacher attacher(this);
  253. GLint location = getUniformLocation(name);
  254. if (size < 1 || size > 4)
  255. throw love::Exception("Invalid variable size: %d (expected 1-4).", size);
  256. switch (size)
  257. {
  258. case 4:
  259. glUniform4fv(location, count, vec);
  260. break;
  261. case 3:
  262. glUniform3fv(location, count, vec);
  263. break;
  264. case 2:
  265. glUniform2fv(location, count, vec);
  266. break;
  267. case 1:
  268. default:
  269. glUniform1fv(location, count, vec);
  270. break;
  271. }
  272. // throw error if needed
  273. checkSetUniformError();
  274. }
  275. void ShaderEffect::sendMatrix(const std::string &name, int size, const GLfloat *m, int count)
  276. {
  277. TemporaryAttacher attacher(this);
  278. GLint location = getUniformLocation(name);
  279. if (size < 2 || size > 4)
  280. {
  281. throw love::Exception("Invalid matrix size: %dx%d "
  282. "(can only set 2x2, 3x3 or 4x4 matrices).", size,size);
  283. }
  284. switch (size)
  285. {
  286. case 4:
  287. glUniformMatrix4fv(location, count, GL_FALSE, m);
  288. break;
  289. case 3:
  290. glUniformMatrix3fv(location, count, GL_FALSE, m);
  291. break;
  292. case 2:
  293. default:
  294. glUniformMatrix2fv(location, count, GL_FALSE, m);
  295. break;
  296. }
  297. // throw error if needed
  298. checkSetUniformError();
  299. }
  300. void ShaderEffect::sendTexture(const std::string &name, GLuint texture)
  301. {
  302. TemporaryAttacher attacher(this);
  303. GLint location = getUniformLocation(name);
  304. GLint texture_unit = getTextureUnit(name);
  305. // bind texture to assigned texture unit and send uniform to bound shader program
  306. bindTextureToUnit(texture, GL_TEXTURE0 + texture_unit, false);
  307. glUniform1i(location, texture_unit);
  308. // reset texture unit
  309. setActiveTextureUnit(GL_TEXTURE0);
  310. // increment global shader texture id counter for this texture unit, if we haven't already
  311. if (_texture_id_list[texture_unit-1] == 0)
  312. ++_texture_id_counters[texture_unit-1];
  313. // store texture id so it can be re-bound to the proper texture unit when necessary
  314. _texture_id_list[texture_unit-1] = texture;
  315. // throw error if needed
  316. checkSetUniformError();
  317. }
  318. void ShaderEffect::sendImage(const std::string &name, const Image &image)
  319. {
  320. sendTexture(name, image.getTextureName());
  321. }
  322. void ShaderEffect::sendCanvas(const std::string &name, const Canvas &canvas)
  323. {
  324. sendTexture(name, canvas.getTextureName());
  325. }
  326. GLint ShaderEffect::getUniformLocation(const std::string &name)
  327. {
  328. std::map<std::string, GLint>::const_iterator it = _uniforms.find(name);
  329. if (it != _uniforms.end())
  330. return it->second;
  331. GLint location = glGetUniformLocation(_program, name.c_str());
  332. if (location == -1)
  333. {
  334. throw love::Exception(
  335. "Cannot get location of shader variable `%s'.\n"
  336. "A common error is to define but not use the variable.", name.c_str());
  337. }
  338. _uniforms[name] = location;
  339. return location;
  340. }
  341. GLint ShaderEffect::getTextureUnit(const std::string &name)
  342. {
  343. std::map<std::string, GLint>::const_iterator it = _texture_unit_pool.find(name);
  344. if (it != _texture_unit_pool.end())
  345. return it->second;
  346. int nextunitindex = 1;
  347. // prefer texture units which are unused by all other shaders
  348. std::vector<int>::iterator nextfreeunit = std::find(_texture_id_counters.begin(), _texture_id_counters.end(), 0);
  349. if (nextfreeunit != _texture_id_counters.end())
  350. nextunitindex = std::distance(_texture_id_counters.begin(), nextfreeunit) + 1; // we don't want to use unit 0
  351. else
  352. {
  353. // no completely unused texture units exist, try to use next free slot in our own list
  354. std::vector<GLuint>::iterator nexttexunit = std::find(_texture_id_list.begin(), _texture_id_list.end(), 0);
  355. if (nexttexunit == _texture_id_list.end())
  356. throw love::Exception("No more texture units available for shader.");
  357. nextunitindex = std::distance(_texture_id_list.begin(), nexttexunit) + 1; // we don't want to use unit 0
  358. }
  359. _texture_unit_pool[name] = nextunitindex;
  360. return nextunitindex;
  361. }
  362. void ShaderEffect::checkSetUniformError()
  363. {
  364. GLenum error_code = glGetError();
  365. if (GL_INVALID_OPERATION == error_code)
  366. {
  367. throw love::Exception(
  368. "Invalid operation:\n"
  369. "- Trying to send the wrong value type to shader variable, or\n"
  370. "- Trying to send array values with wrong dimension, or\n"
  371. "- Invalid variable name.");
  372. }
  373. }
  374. } // opengl
  375. } // graphics
  376. } // love