Shader.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. /**
  2. * Copyright (c) 2006-2020 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. // LOVE
  21. #include "common/config.h"
  22. #include "Shader.h"
  23. #include "Graphics.h"
  24. #include "graphics/vertex.h"
  25. // C++
  26. #include <algorithm>
  27. #include <limits>
  28. #include <sstream>
  29. namespace love
  30. {
  31. namespace graphics
  32. {
  33. namespace opengl
  34. {
  35. static bool isBuffer(Shader::UniformType utype)
  36. {
  37. return utype == Shader::UNIFORM_TEXELBUFFER || utype == Shader::UNIFORM_STORAGEBUFFER;
  38. }
  39. Shader::Shader(love::graphics::ShaderStage *vertex, love::graphics::ShaderStage *pixel)
  40. : love::graphics::Shader(vertex, pixel)
  41. , program(0)
  42. , builtinUniforms()
  43. , builtinUniformInfo()
  44. , builtinAttributes()
  45. , lastPointSize(0.0f)
  46. {
  47. // load shader source and create program object
  48. loadVolatile();
  49. }
  50. Shader::~Shader()
  51. {
  52. unloadVolatile();
  53. for (const auto &p : uniforms)
  54. {
  55. // Allocated with malloc().
  56. if (p.second.data != nullptr)
  57. free(p.second.data);
  58. if (p.second.baseType == UNIFORM_SAMPLER)
  59. {
  60. for (int i = 0; i < p.second.count; i++)
  61. {
  62. if (p.second.textures[i] != nullptr)
  63. p.second.textures[i]->release();
  64. }
  65. delete[] p.second.textures;
  66. }
  67. else if (isBuffer(p.second.baseType))
  68. {
  69. for (int i = 0; i < p.second.count; i++)
  70. {
  71. if (p.second.buffers[i] != nullptr)
  72. p.second.buffers[i]->release();
  73. }
  74. delete[] p.second.buffers;
  75. }
  76. }
  77. }
  78. void Shader::mapActiveUniforms()
  79. {
  80. // Built-in uniform locations default to -1 (nonexistent.)
  81. for (int i = 0; i < int(BUILTIN_MAX_ENUM); i++)
  82. {
  83. builtinUniforms[i] = -1;
  84. builtinUniformInfo[i] = nullptr;
  85. }
  86. GLint activeprogram = 0;
  87. glGetIntegerv(GL_CURRENT_PROGRAM, &activeprogram);
  88. gl.useProgram(program);
  89. GLint numuniforms;
  90. glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &numuniforms);
  91. GLchar cname[256];
  92. const GLint bufsize = (GLint) (sizeof(cname) / sizeof(GLchar));
  93. std::map<std::string, UniformInfo> olduniforms = uniforms;
  94. uniforms.clear();
  95. for (int uindex = 0; uindex < numuniforms; uindex++)
  96. {
  97. GLsizei namelen = 0;
  98. GLenum gltype = 0;
  99. UniformInfo u = {};
  100. glGetActiveUniform(program, (GLuint) uindex, bufsize, &namelen, &u.count, &gltype, cname);
  101. u.name = std::string(cname, (size_t) namelen);
  102. u.location = glGetUniformLocation(program, u.name.c_str());
  103. u.baseType = getUniformBaseType(gltype);
  104. u.textureType = getUniformTextureType(gltype);
  105. u.texelBufferType = getUniformTexelBufferType(gltype);
  106. u.isDepthSampler = isDepthTextureType(gltype);
  107. if (u.baseType == UNIFORM_MATRIX)
  108. u.matrix = getMatrixSize(gltype);
  109. else
  110. u.components = getUniformTypeComponents(gltype);
  111. // glGetActiveUniform appends "[0]" to the end of array uniform names...
  112. if (u.name.length() > 3)
  113. {
  114. size_t findpos = u.name.find("[0]");
  115. if (findpos != std::string::npos && findpos == u.name.length() - 3)
  116. u.name.erase(u.name.length() - 3);
  117. }
  118. // If this is a built-in (LOVE-created) uniform, store the location.
  119. BuiltinUniform builtin = BUILTIN_MAX_ENUM;
  120. if (getConstant(u.name.c_str(), builtin))
  121. builtinUniforms[int(builtin)] = u.location;
  122. if (u.location == -1)
  123. continue;
  124. if ((u.baseType == UNIFORM_SAMPLER && builtin != BUILTIN_TEXTURE_MAIN) || u.baseType == UNIFORM_TEXELBUFFER)
  125. {
  126. TextureUnit unit;
  127. unit.type = u.textureType;
  128. unit.active = true;
  129. if (u.baseType == UNIFORM_TEXELBUFFER)
  130. {
  131. unit.isTexelBuffer = true;
  132. unit.texture = gl.getDefaultTexelBuffer();
  133. }
  134. else
  135. {
  136. unit.isTexelBuffer = false;
  137. unit.texture = gl.getDefaultTexture(u.textureType);
  138. }
  139. for (int i = 0; i < u.count; i++)
  140. textureUnits.push_back(unit);
  141. }
  142. // Make sure previously set uniform data is preserved, and shader-
  143. // initialized values are retrieved.
  144. auto oldu = olduniforms.find(u.name);
  145. if (oldu != olduniforms.end())
  146. {
  147. u.data = oldu->second.data;
  148. u.dataSize = oldu->second.dataSize;
  149. u.textures = oldu->second.textures;
  150. updateUniform(&u, u.count, true);
  151. }
  152. else
  153. {
  154. u.dataSize = 0;
  155. switch (u.baseType)
  156. {
  157. case UNIFORM_FLOAT:
  158. u.dataSize = sizeof(float) * u.components * u.count;
  159. u.data = malloc(u.dataSize);
  160. break;
  161. case UNIFORM_INT:
  162. case UNIFORM_BOOL:
  163. case UNIFORM_SAMPLER:
  164. case UNIFORM_TEXELBUFFER:
  165. u.dataSize = sizeof(int) * u.components * u.count;
  166. u.data = malloc(u.dataSize);
  167. break;
  168. case UNIFORM_UINT:
  169. u.dataSize = sizeof(unsigned int) * u.components * u.count;
  170. u.data = malloc(u.dataSize);
  171. break;
  172. case UNIFORM_MATRIX:
  173. u.dataSize = sizeof(float) * ((size_t)u.matrix.rows * u.matrix.columns) * u.count;
  174. u.data = malloc(u.dataSize);
  175. break;
  176. default:
  177. break;
  178. }
  179. if (u.dataSize > 0)
  180. {
  181. memset(u.data, 0, u.dataSize);
  182. if (u.baseType == UNIFORM_SAMPLER || u.baseType == UNIFORM_TEXELBUFFER)
  183. {
  184. int startunit = (int) textureUnits.size() - u.count;
  185. if (builtin == BUILTIN_TEXTURE_MAIN)
  186. startunit = 0;
  187. for (int i = 0; i < u.count; i++)
  188. u.ints[i] = startunit + i;
  189. glUniform1iv(u.location, u.count, u.ints);
  190. if (u.baseType == UNIFORM_TEXELBUFFER)
  191. {
  192. u.buffers = new love::graphics::Buffer*[u.count];
  193. memset(u.buffers, 0, sizeof(Buffer *) * u.count);
  194. }
  195. else
  196. {
  197. u.textures = new love::graphics::Texture*[u.count];
  198. memset(u.textures, 0, sizeof(Texture *) * u.count);
  199. }
  200. }
  201. }
  202. size_t offset = 0;
  203. // Store any shader-initialized values in our own memory.
  204. for (int i = 0; i < u.count; i++)
  205. {
  206. GLint location = u.location;
  207. if (u.count > 1)
  208. {
  209. std::ostringstream ss;
  210. ss << i;
  211. std::string indexname = u.name + "[" + ss.str() + "]";
  212. location = glGetUniformLocation(program, indexname.c_str());
  213. }
  214. if (location == -1)
  215. continue;
  216. switch (u.baseType)
  217. {
  218. case UNIFORM_FLOAT:
  219. glGetUniformfv(program, location, &u.floats[offset]);
  220. offset += u.components;
  221. break;
  222. case UNIFORM_INT:
  223. case UNIFORM_BOOL:
  224. glGetUniformiv(program, location, &u.ints[offset]);
  225. offset += u.components;
  226. break;
  227. case UNIFORM_UINT:
  228. glGetUniformuiv(program, location, &u.uints[offset]);
  229. offset += u.components;
  230. break;
  231. case UNIFORM_MATRIX:
  232. glGetUniformfv(program, location, &u.floats[offset]);
  233. offset += (size_t)u.matrix.rows * u.matrix.columns;
  234. break;
  235. default:
  236. break;
  237. }
  238. }
  239. }
  240. uniforms[u.name] = u;
  241. if (builtin != BUILTIN_MAX_ENUM)
  242. builtinUniformInfo[(int)builtin] = &uniforms[u.name];
  243. if (u.baseType == UNIFORM_SAMPLER)
  244. {
  245. // Make sure all stored textures have their Volatiles loaded before
  246. // the sendTextures call, since it calls getHandle().
  247. for (int i = 0; i < u.count; i++)
  248. {
  249. if (u.textures[i] == nullptr)
  250. continue;
  251. Volatile *v = dynamic_cast<Volatile *>(u.textures[i]);
  252. if (v != nullptr)
  253. v->loadVolatile();
  254. }
  255. sendTextures(&u, u.textures, u.count, true);
  256. }
  257. else if (u.baseType == UNIFORM_TEXELBUFFER)
  258. {
  259. for (int i = 0; i < u.count; i++)
  260. {
  261. if (u.buffers[i] == nullptr)
  262. continue;
  263. Volatile *v = dynamic_cast<Volatile *>(u.buffers[i]);
  264. if (v != nullptr)
  265. v->loadVolatile();
  266. }
  267. sendBuffers(&u, u.buffers, u.count, true);
  268. }
  269. }
  270. if (gl.isBufferUsageSupported(BUFFERUSAGE_SHADER_STORAGE))
  271. {
  272. GLint numstoragebuffers = 0;
  273. glGetProgramInterfaceiv(program, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &numstoragebuffers);
  274. char namebuffer[2048] = { '\0' };
  275. for (int sindex = 0; sindex < numstoragebuffers; sindex++)
  276. {
  277. UniformInfo u = {};
  278. u.baseType = UNIFORM_STORAGEBUFFER;
  279. GLsizei namelength = 0;
  280. glGetProgramResourceName(program, GL_SHADER_STORAGE_BLOCK, sindex, 2048, &namelength, namebuffer);
  281. u.name = std::string(namebuffer, namelength);
  282. u.count = 1;
  283. const auto reflectionit = validationReflection.storageBuffers.find(u.name);
  284. if (reflectionit != validationReflection.storageBuffers.end())
  285. {
  286. u.bufferStride = reflectionit->second.stride;
  287. u.bufferMemberCount = reflectionit->second.memberCount;
  288. }
  289. // Make sure previously set uniform data is preserved, and shader-
  290. // initialized values are retrieved.
  291. auto oldu = olduniforms.find(u.name);
  292. if (oldu != olduniforms.end())
  293. {
  294. u.data = oldu->second.data;
  295. u.dataSize = oldu->second.dataSize;
  296. u.buffers = oldu->second.buffers;
  297. }
  298. else
  299. {
  300. u.dataSize = sizeof(int) * 1;
  301. u.data = malloc(u.dataSize);
  302. u.ints[0] = -1;
  303. u.buffers = new love::graphics::Buffer * [u.count];
  304. memset(u.buffers, 0, sizeof(Buffer*)* u.count);
  305. }
  306. GLenum props[] = { GL_BUFFER_BINDING };
  307. glGetProgramResourceiv(program, GL_SHADER_STORAGE_BLOCK, sindex, 1, props, 1, nullptr, u.ints);
  308. BufferBinding binding;
  309. binding.bindingindex = u.ints[0];
  310. binding.buffer = gl.getDefaultStorageBuffer();
  311. if (binding.bindingindex >= 0)
  312. {
  313. int activeindex = (int)activeStorageBufferBindings.size();
  314. storageBufferBindingIndexToActiveBinding[binding.bindingindex] = activeindex;
  315. activeStorageBufferBindings.push_back(binding);
  316. }
  317. uniforms[u.name] = u;
  318. for (int i = 0; i < u.count; i++)
  319. {
  320. if (u.buffers[i] == nullptr)
  321. continue;
  322. Volatile* v = dynamic_cast<Volatile*>(u.buffers[i]);
  323. if (v != nullptr)
  324. v->loadVolatile();
  325. }
  326. sendBuffers(&u, u.buffers, u.count, true);
  327. }
  328. }
  329. // Make sure uniforms that existed before but don't exist anymore are
  330. // cleaned up. This theoretically shouldn't happen, but...
  331. for (const auto &p : olduniforms)
  332. {
  333. if (uniforms.find(p.first) == uniforms.end())
  334. {
  335. if (p.second.data != nullptr)
  336. free(p.second.data);
  337. if (p.second.baseType == UNIFORM_SAMPLER)
  338. {
  339. for (int i = 0; i < p.second.count; i++)
  340. {
  341. if (p.second.textures[i] != nullptr)
  342. p.second.textures[i]->release();
  343. }
  344. delete[] p.second.textures;
  345. }
  346. else if (isBuffer(p.second.baseType))
  347. {
  348. for (int i = 0; i < p.second.count; i++)
  349. {
  350. if (p.second.buffers[i] != nullptr)
  351. p.second.buffers[i]->release();
  352. }
  353. delete[] p.second.buffers;
  354. }
  355. }
  356. }
  357. gl.useProgram(activeprogram);
  358. }
  359. bool Shader::loadVolatile()
  360. {
  361. OpenGL::TempDebugGroup debuggroup("Shader load");
  362. lastPointSize = -1.0f;
  363. // zero out active texture list
  364. textureUnits.clear();
  365. textureUnits.push_back(TextureUnit());
  366. storageBufferBindingIndexToActiveBinding.resize(gl.getMaxShaderStorageBufferBindings(), -1);
  367. activeStorageBufferBindings.clear();
  368. for (const auto &stage : stages)
  369. {
  370. if (stage.get() != nullptr)
  371. stage->loadVolatile();
  372. }
  373. program = glCreateProgram();
  374. if (program == 0)
  375. throw love::Exception("Cannot create shader program object.");
  376. for (const auto &stage : stages)
  377. {
  378. if (stage.get() != nullptr)
  379. glAttachShader(program, (GLuint) stage->getHandle());
  380. }
  381. // Bind generic vertex attribute indices to names in the shader.
  382. for (int i = 0; i < int(ATTRIB_MAX_ENUM); i++)
  383. {
  384. const char *name = nullptr;
  385. if (graphics::getConstant((BuiltinVertexAttribute) i, name))
  386. glBindAttribLocation(program, i, (const GLchar *) name);
  387. }
  388. glLinkProgram(program);
  389. GLint status;
  390. glGetProgramiv(program, GL_LINK_STATUS, &status);
  391. if (status == GL_FALSE)
  392. {
  393. std::string warnings = getProgramWarnings();
  394. glDeleteProgram(program);
  395. program = 0;
  396. throw love::Exception("Cannot link shader program object:\n%s", warnings.c_str());
  397. }
  398. // Get all active uniform variables in this shader from OpenGL.
  399. mapActiveUniforms();
  400. for (int i = 0; i < int(ATTRIB_MAX_ENUM); i++)
  401. {
  402. const char *name = nullptr;
  403. if (graphics::getConstant(BuiltinVertexAttribute(i), name))
  404. builtinAttributes[i] = glGetAttribLocation(program, name);
  405. else
  406. builtinAttributes[i] = -1;
  407. }
  408. if (current == this)
  409. {
  410. // make sure glUseProgram gets called.
  411. current = nullptr;
  412. attach();
  413. }
  414. return true;
  415. }
  416. void Shader::unloadVolatile()
  417. {
  418. if (program != 0)
  419. {
  420. if (current == this)
  421. gl.useProgram(0);
  422. glDeleteProgram(program);
  423. program = 0;
  424. }
  425. // active texture list is probably invalid, clear it
  426. textureUnits.clear();
  427. textureUnits.push_back(TextureUnit());
  428. attributes.clear();
  429. // And the locations of any built-in uniform variables.
  430. for (int i = 0; i < int(BUILTIN_MAX_ENUM); i++)
  431. builtinUniforms[i] = -1;
  432. }
  433. std::string Shader::getProgramWarnings() const
  434. {
  435. GLint strsize, nullpos;
  436. glGetProgramiv(program, GL_INFO_LOG_LENGTH, &strsize);
  437. if (strsize == 0)
  438. return "";
  439. char *tempstr = new char[strsize];
  440. // be extra sure that the error string will be 0-terminated
  441. memset(tempstr, '\0', strsize);
  442. glGetProgramInfoLog(program, strsize, &nullpos, tempstr);
  443. tempstr[nullpos] = '\0';
  444. std::string warnings(tempstr);
  445. delete[] tempstr;
  446. return warnings;
  447. }
  448. std::string Shader::getWarnings() const
  449. {
  450. std::string warnings;
  451. const char *stagestr;
  452. for (const auto &stage : stages)
  453. {
  454. if (stage.get() == nullptr)
  455. continue;
  456. const std::string &stagewarnings = stage->getWarnings();
  457. if (ShaderStage::getConstant(stage->getStageType(), stagestr))
  458. warnings += std::string(stagestr) + std::string(" shader:\n") + stagewarnings;
  459. }
  460. warnings += getProgramWarnings();
  461. return warnings;
  462. }
  463. void Shader::attach()
  464. {
  465. if (current != this)
  466. {
  467. Graphics::flushBatchedDrawsGlobal();
  468. gl.useProgram(program);
  469. current = this;
  470. // retain/release happens in Graphics::setShader.
  471. // Make sure all textures are bound to their respective texture units.
  472. for (int i = 0; i < (int) textureUnits.size(); ++i)
  473. {
  474. const TextureUnit &unit = textureUnits[i];
  475. if (unit.active)
  476. {
  477. if (unit.isTexelBuffer)
  478. gl.bindBufferTextureToUnit(unit.texture, i, false, false);
  479. else
  480. gl.bindTextureToUnit(unit.type, unit.texture, i, false, false);
  481. }
  482. }
  483. for (auto bufferbinding : activeStorageBufferBindings)
  484. gl.bindIndexedBuffer(bufferbinding.buffer, BUFFERUSAGE_SHADER_STORAGE, bufferbinding.bindingindex);
  485. // send any pending uniforms to the shader program.
  486. for (const auto &p : pendingUniformUpdates)
  487. updateUniform(p.first, p.second, true);
  488. pendingUniformUpdates.clear();
  489. }
  490. }
  491. const Shader::UniformInfo *Shader::getUniformInfo(const std::string &name) const
  492. {
  493. const auto it = uniforms.find(name);
  494. if (it == uniforms.end())
  495. return nullptr;
  496. return &(it->second);
  497. }
  498. const Shader::UniformInfo *Shader::getUniformInfo(BuiltinUniform builtin) const
  499. {
  500. return builtinUniformInfo[(int)builtin];
  501. }
  502. void Shader::updateUniform(const UniformInfo *info, int count)
  503. {
  504. updateUniform(info, count, false);
  505. }
  506. void Shader::updateUniform(const UniformInfo *info, int count, bool internalupdate)
  507. {
  508. if (current != this && !internalupdate)
  509. {
  510. pendingUniformUpdates.push_back(std::make_pair(info, count));
  511. return;
  512. }
  513. if (!internalupdate)
  514. flushBatchedDraws();
  515. int location = info->location;
  516. UniformType type = info->baseType;
  517. if (type == UNIFORM_FLOAT)
  518. {
  519. switch (info->components)
  520. {
  521. case 1:
  522. glUniform1fv(location, count, info->floats);
  523. break;
  524. case 2:
  525. glUniform2fv(location, count, info->floats);
  526. break;
  527. case 3:
  528. glUniform3fv(location, count, info->floats);
  529. break;
  530. case 4:
  531. glUniform4fv(location, count, info->floats);
  532. break;
  533. }
  534. }
  535. else if (type == UNIFORM_INT || type == UNIFORM_BOOL || type == UNIFORM_SAMPLER || type == UNIFORM_TEXELBUFFER)
  536. {
  537. switch (info->components)
  538. {
  539. case 1:
  540. glUniform1iv(location, count, info->ints);
  541. break;
  542. case 2:
  543. glUniform2iv(location, count, info->ints);
  544. break;
  545. case 3:
  546. glUniform3iv(location, count, info->ints);
  547. break;
  548. case 4:
  549. glUniform4iv(location, count, info->ints);
  550. break;
  551. }
  552. }
  553. else if (type == UNIFORM_UINT)
  554. {
  555. switch (info->components)
  556. {
  557. case 1:
  558. glUniform1uiv(location, count, info->uints);
  559. break;
  560. case 2:
  561. glUniform2uiv(location, count, info->uints);
  562. break;
  563. case 3:
  564. glUniform3uiv(location, count, info->uints);
  565. break;
  566. case 4:
  567. glUniform4uiv(location, count, info->uints);
  568. break;
  569. }
  570. }
  571. else if (type == UNIFORM_MATRIX)
  572. {
  573. int columns = info->matrix.columns;
  574. int rows = info->matrix.rows;
  575. if (columns == 2 && rows == 2)
  576. glUniformMatrix2fv(location, count, GL_FALSE, info->floats);
  577. else if (columns == 3 && rows == 3)
  578. glUniformMatrix3fv(location, count, GL_FALSE, info->floats);
  579. else if (columns == 4 && rows == 4)
  580. glUniformMatrix4fv(location, count, GL_FALSE, info->floats);
  581. else if (columns == 2 && rows == 3)
  582. glUniformMatrix2x3fv(location, count, GL_FALSE, info->floats);
  583. else if (columns == 2 && rows == 4)
  584. glUniformMatrix2x4fv(location, count, GL_FALSE, info->floats);
  585. else if (columns == 3 && rows == 2)
  586. glUniformMatrix3x2fv(location, count, GL_FALSE, info->floats);
  587. else if (columns == 3 && rows == 4)
  588. glUniformMatrix3x4fv(location, count, GL_FALSE, info->floats);
  589. else if (columns == 4 && rows == 2)
  590. glUniformMatrix4x2fv(location, count, GL_FALSE, info->floats);
  591. else if (columns == 4 && rows == 3)
  592. glUniformMatrix4x3fv(location, count, GL_FALSE, info->floats);
  593. }
  594. }
  595. void Shader::sendTextures(const UniformInfo *info, love::graphics::Texture **textures, int count)
  596. {
  597. Shader::sendTextures(info, textures, count, false);
  598. }
  599. void Shader::sendTextures(const UniformInfo *info, love::graphics::Texture **textures, int count, bool internalUpdate)
  600. {
  601. if (info->baseType != UNIFORM_SAMPLER)
  602. return;
  603. bool shaderactive = current == this;
  604. if (!internalUpdate && shaderactive)
  605. flushBatchedDraws();
  606. count = std::min(count, info->count);
  607. // Bind the textures to the texture units.
  608. for (int i = 0; i < count; i++)
  609. {
  610. love::graphics::Texture *tex = textures[i];
  611. if (tex != nullptr)
  612. {
  613. const SamplerState &sampler = tex->getSamplerState();
  614. if (!tex->isReadable())
  615. {
  616. if (internalUpdate)
  617. continue;
  618. else
  619. throw love::Exception("Textures with non-readable formats cannot be sampled from in a shader.");
  620. }
  621. else if (info->isDepthSampler != sampler.depthSampleMode.hasValue)
  622. {
  623. if (internalUpdate)
  624. continue;
  625. else if (info->isDepthSampler)
  626. throw love::Exception("Depth comparison samplers in shaders can only be used with depth textures which have depth comparison set.");
  627. else
  628. throw love::Exception("Depth textures which have depth comparison set can only be used with depth/shadow samplers in shaders.");
  629. }
  630. else if (tex->getTextureType() != info->textureType)
  631. {
  632. if (internalUpdate)
  633. continue;
  634. else
  635. {
  636. const char *textypestr = "unknown";
  637. const char *shadertextypestr = "unknown";
  638. Texture::getConstant(tex->getTextureType(), textypestr);
  639. Texture::getConstant(info->textureType, shadertextypestr);
  640. throw love::Exception("Texture's type (%s) must match the type of %s (%s).", textypestr, info->name.c_str(), shadertextypestr);
  641. }
  642. }
  643. tex->retain();
  644. }
  645. if (info->textures[i] != nullptr)
  646. info->textures[i]->release();
  647. info->textures[i] = tex;
  648. GLuint gltex = 0;
  649. if (textures[i] != nullptr)
  650. gltex = (GLuint) tex->getHandle();
  651. else
  652. gltex = gl.getDefaultTexture(info->textureType);
  653. int texunit = info->ints[i];
  654. if (shaderactive)
  655. gl.bindTextureToUnit(info->textureType, gltex, texunit, false, false);
  656. // Store texture id so it can be re-bound to the texture unit later.
  657. textureUnits[texunit].texture = gltex;
  658. }
  659. }
  660. void Shader::sendBuffers(const UniformInfo *info, love::graphics::Buffer **buffers, int count)
  661. {
  662. Shader::sendBuffers(info, buffers, count, false);
  663. }
  664. static bool isTexelBufferTypeCompatible(DataBaseType a, DataBaseType b)
  665. {
  666. if (a == DATA_BASETYPE_FLOAT || a == DATA_BASETYPE_UNORM || a == DATA_BASETYPE_SNORM)
  667. return b == DATA_BASETYPE_FLOAT || b == DATA_BASETYPE_UNORM || b == DATA_BASETYPE_SNORM;
  668. if (a == DATA_BASETYPE_INT && b == DATA_BASETYPE_INT)
  669. return true;
  670. if (a == DATA_BASETYPE_UINT && b == DATA_BASETYPE_UINT)
  671. return true;
  672. return false;
  673. }
  674. void Shader::sendBuffers(const UniformInfo *info, love::graphics::Buffer **buffers, int count, bool internalUpdate)
  675. {
  676. uint32 requiredtypeflags = 0;
  677. bool texelbinding = info->baseType == UNIFORM_TEXELBUFFER;
  678. bool storagebinding = info->baseType == UNIFORM_STORAGEBUFFER;
  679. if (texelbinding)
  680. requiredtypeflags = BUFFERUSAGEFLAG_TEXEL;
  681. else if (storagebinding)
  682. requiredtypeflags = BUFFERUSAGEFLAG_SHADER_STORAGE;
  683. if (requiredtypeflags == 0)
  684. return;
  685. bool shaderactive = current == this;
  686. if (!internalUpdate && shaderactive)
  687. flushBatchedDraws();
  688. count = std::min(count, info->count);
  689. // Bind the textures to the texture units.
  690. for (int i = 0; i < count; i++)
  691. {
  692. love::graphics::Buffer *buffer = buffers[i];
  693. if (buffer != nullptr)
  694. {
  695. if ((buffer->getUsageFlags() & requiredtypeflags) == 0)
  696. {
  697. if (internalUpdate)
  698. continue;
  699. else if (texelbinding)
  700. throw love::Exception("Shader uniform '%s' is a texel buffer, but the given Buffer was not created with texel buffer capabilities.", info->name.c_str());
  701. else if (storagebinding)
  702. throw love::Exception("Shader uniform '%s' is a shader storage buffer block, but the given Buffer was not created with shader storage buffer capabilities.", info->name.c_str());
  703. else
  704. throw love::Exception("Shader uniform '%s' does not match the types supported by the given Buffer.", info->name.c_str());
  705. }
  706. if (texelbinding)
  707. {
  708. DataBaseType basetype = buffer->getDataMember(0).info.baseType;
  709. if (!isTexelBufferTypeCompatible(basetype, info->texelBufferType))
  710. {
  711. if (internalUpdate)
  712. continue;
  713. else
  714. throw love::Exception("Texel buffer's data format base type must match the variable declared in the shader.");
  715. }
  716. }
  717. else if (storagebinding)
  718. {
  719. if (info->bufferStride != buffer->getArrayStride())
  720. {
  721. if (internalUpdate)
  722. continue;
  723. else
  724. throw love::Exception("Shader storage block '%s' has an array stride of %d bytes, but the given Buffer has an array stride of %d bytes.",
  725. info->name.c_str(), info->bufferStride, buffer->getArrayStride());
  726. }
  727. else if (info->bufferMemberCount != buffer->getDataMembers().size())
  728. {
  729. if (internalUpdate)
  730. continue;
  731. else
  732. throw love::Exception("Shader storage block '%s' has a struct with %d fields, but the given Buffer has a format with %d members.",
  733. info->name.c_str(), info->bufferMemberCount, buffer->getDataMembers().size());
  734. }
  735. }
  736. buffer->retain();
  737. }
  738. if (info->buffers[i] != nullptr)
  739. info->buffers[i]->release();
  740. info->buffers[i] = buffer;
  741. if (texelbinding)
  742. {
  743. GLuint gltex = 0;
  744. if (buffers[i] != nullptr)
  745. gltex = (GLuint) buffer->getTexelBufferHandle();
  746. else
  747. gltex = gl.getDefaultTexelBuffer();
  748. int texunit = info->ints[i];
  749. if (shaderactive)
  750. gl.bindBufferTextureToUnit(gltex, texunit, false, false);
  751. // Store texture id so it can be re-bound to the texture unit later.
  752. textureUnits[texunit].texture = gltex;
  753. }
  754. else if (storagebinding)
  755. {
  756. int bindingindex = info->ints[i];
  757. GLuint glbuffer = 0;
  758. if (buffers[i] != nullptr)
  759. glbuffer = (GLuint) buffer->getHandle();
  760. else
  761. glbuffer = gl.getDefaultStorageBuffer();
  762. if (shaderactive)
  763. gl.bindIndexedBuffer(glbuffer, BUFFERUSAGE_SHADER_STORAGE, bindingindex);
  764. int activeindex = storageBufferBindingIndexToActiveBinding[bindingindex];
  765. if (activeindex >= 0)
  766. activeStorageBufferBindings[activeindex].buffer = glbuffer;
  767. }
  768. }
  769. }
  770. void Shader::flushBatchedDraws() const
  771. {
  772. if (current == this)
  773. Graphics::flushBatchedDrawsGlobal();
  774. }
  775. bool Shader::hasUniform(const std::string &name) const
  776. {
  777. return uniforms.find(name) != uniforms.end();
  778. }
  779. ptrdiff_t Shader::getHandle() const
  780. {
  781. return program;
  782. }
  783. int Shader::getVertexAttributeIndex(const std::string &name)
  784. {
  785. auto it = attributes.find(name);
  786. if (it != attributes.end())
  787. return it->second;
  788. GLint location = glGetAttribLocation(program, name.c_str());
  789. attributes[name] = location;
  790. return location;
  791. }
  792. void Shader::setVideoTextures(love::graphics::Texture *ytexture, love::graphics::Texture *cbtexture, love::graphics::Texture *crtexture)
  793. {
  794. const BuiltinUniform builtins[3] = {
  795. BUILTIN_TEXTURE_VIDEO_Y,
  796. BUILTIN_TEXTURE_VIDEO_CB,
  797. BUILTIN_TEXTURE_VIDEO_CR,
  798. };
  799. love::graphics::Texture *textures[3] = {ytexture, cbtexture, crtexture};
  800. for (int i = 0; i < 3; i++)
  801. {
  802. const UniformInfo *info = builtinUniformInfo[builtins[i]];
  803. if (info != nullptr)
  804. sendTextures(info, &textures[i], 1, true);
  805. }
  806. }
  807. void Shader::updatePointSize(float size)
  808. {
  809. if (size == lastPointSize || current != this)
  810. return;
  811. GLint location = builtinUniforms[BUILTIN_POINT_SIZE];
  812. if (location >= 0)
  813. glUniform1f(location, size);
  814. lastPointSize = size;
  815. }
  816. void Shader::updateBuiltinUniforms(love::graphics::Graphics *gfx, int viewportW, int viewportH)
  817. {
  818. if (current != this)
  819. return;
  820. if (GLAD_ES_VERSION_2_0)
  821. updatePointSize(gl.getPointSize());
  822. BuiltinUniformData data;
  823. data.transformMatrix = gfx->getTransform();
  824. data.projectionMatrix = gfx->getProjection();
  825. // The normal matrix is the transpose of the inverse of the rotation portion
  826. // (top-left 3x3) of the transform matrix.
  827. {
  828. Matrix3 normalmatrix = Matrix3(data.transformMatrix).transposedInverse();
  829. const float *e = normalmatrix.getElements();
  830. for (int i = 0; i < 3; i++)
  831. {
  832. data.normalMatrix[i].x = e[i * 3 + 0];
  833. data.normalMatrix[i].y = e[i * 3 + 1];
  834. data.normalMatrix[i].z = e[i * 3 + 2];
  835. data.normalMatrix[i].w = 0.0f;
  836. }
  837. }
  838. data.screenSizeParams.x = viewportW;
  839. data.screenSizeParams.y = viewportH;
  840. // The shader does pixcoord.y = gl_FragCoord.y * params.z + params.w.
  841. // This lets us flip pixcoord.y when needed, to be consistent (drawing
  842. // with no RT active makes the pixel coordinates y-flipped.)
  843. if (gfx->isRenderTargetActive())
  844. {
  845. // No flipping: pixcoord.y = gl_FragCoord.y * 1.0 + 0.0.
  846. data.screenSizeParams.z = 1.0f;
  847. data.screenSizeParams.w = 0.0f;
  848. }
  849. else
  850. {
  851. // gl_FragCoord.y is flipped when drawing to the screen, so we
  852. // un-flip: pixcoord.y = gl_FragCoord.y * -1.0 + height.
  853. data.screenSizeParams.z = -1.0f;
  854. data.screenSizeParams.w = viewportH;
  855. }
  856. data.constantColor = gfx->getColor();
  857. gammaCorrectColor(data.constantColor);
  858. GLint location = builtinUniforms[BUILTIN_UNIFORMS_PER_DRAW];
  859. if (location >= 0)
  860. glUniform4fv(location, 13, (const GLfloat *) &data);
  861. }
  862. int Shader::getUniformTypeComponents(GLenum type) const
  863. {
  864. UniformType basetype = getUniformBaseType(type);
  865. if (basetype == UNIFORM_SAMPLER || basetype == UNIFORM_TEXELBUFFER)
  866. return 1;
  867. switch (type)
  868. {
  869. case GL_INT:
  870. case GL_UNSIGNED_INT:
  871. case GL_FLOAT:
  872. case GL_BOOL:
  873. return 1;
  874. case GL_INT_VEC2:
  875. case GL_UNSIGNED_INT_VEC2:
  876. case GL_FLOAT_VEC2:
  877. case GL_FLOAT_MAT2:
  878. case GL_BOOL_VEC2:
  879. return 2;
  880. case GL_INT_VEC3:
  881. case GL_UNSIGNED_INT_VEC3:
  882. case GL_FLOAT_VEC3:
  883. case GL_FLOAT_MAT3:
  884. case GL_BOOL_VEC3:
  885. return 3;
  886. case GL_INT_VEC4:
  887. case GL_UNSIGNED_INT_VEC4:
  888. case GL_FLOAT_VEC4:
  889. case GL_FLOAT_MAT4:
  890. case GL_BOOL_VEC4:
  891. return 4;
  892. default:
  893. return 1;
  894. }
  895. }
  896. Shader::MatrixSize Shader::getMatrixSize(GLenum type) const
  897. {
  898. MatrixSize m;
  899. switch (type)
  900. {
  901. case GL_FLOAT_MAT2:
  902. m.columns = m.rows = 2;
  903. break;
  904. case GL_FLOAT_MAT3:
  905. m.columns = m.rows = 3;
  906. break;
  907. case GL_FLOAT_MAT4:
  908. m.columns = m.rows = 4;
  909. break;
  910. case GL_FLOAT_MAT2x3:
  911. m.columns = 2;
  912. m.rows = 3;
  913. break;
  914. case GL_FLOAT_MAT2x4:
  915. m.columns = 2;
  916. m.rows = 4;
  917. break;
  918. case GL_FLOAT_MAT3x2:
  919. m.columns = 3;
  920. m.rows = 2;
  921. break;
  922. case GL_FLOAT_MAT3x4:
  923. m.columns = 3;
  924. m.rows = 4;
  925. break;
  926. case GL_FLOAT_MAT4x2:
  927. m.columns = 4;
  928. m.rows = 2;
  929. break;
  930. case GL_FLOAT_MAT4x3:
  931. m.columns = 4;
  932. m.rows = 3;
  933. break;
  934. }
  935. return m;
  936. }
  937. Shader::UniformType Shader::getUniformBaseType(GLenum type) const
  938. {
  939. switch (type)
  940. {
  941. case GL_INT:
  942. case GL_INT_VEC2:
  943. case GL_INT_VEC3:
  944. case GL_INT_VEC4:
  945. return UNIFORM_INT;
  946. case GL_UNSIGNED_INT:
  947. case GL_UNSIGNED_INT_VEC2:
  948. case GL_UNSIGNED_INT_VEC3:
  949. case GL_UNSIGNED_INT_VEC4:
  950. return UNIFORM_UINT;
  951. case GL_FLOAT:
  952. case GL_FLOAT_VEC2:
  953. case GL_FLOAT_VEC3:
  954. case GL_FLOAT_VEC4:
  955. return UNIFORM_FLOAT;
  956. case GL_FLOAT_MAT2:
  957. case GL_FLOAT_MAT3:
  958. case GL_FLOAT_MAT4:
  959. case GL_FLOAT_MAT2x3:
  960. case GL_FLOAT_MAT2x4:
  961. case GL_FLOAT_MAT3x2:
  962. case GL_FLOAT_MAT3x4:
  963. case GL_FLOAT_MAT4x2:
  964. case GL_FLOAT_MAT4x3:
  965. return UNIFORM_MATRIX;
  966. case GL_BOOL:
  967. case GL_BOOL_VEC2:
  968. case GL_BOOL_VEC3:
  969. case GL_BOOL_VEC4:
  970. return UNIFORM_BOOL;
  971. case GL_SAMPLER_1D:
  972. case GL_SAMPLER_1D_SHADOW:
  973. case GL_SAMPLER_1D_ARRAY:
  974. case GL_SAMPLER_1D_ARRAY_SHADOW:
  975. case GL_SAMPLER_2D:
  976. case GL_SAMPLER_2D_MULTISAMPLE:
  977. case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
  978. case GL_SAMPLER_2D_RECT:
  979. case GL_SAMPLER_2D_RECT_SHADOW:
  980. case GL_SAMPLER_2D_SHADOW:
  981. case GL_SAMPLER_2D_ARRAY:
  982. case GL_SAMPLER_2D_ARRAY_SHADOW:
  983. case GL_SAMPLER_3D:
  984. case GL_SAMPLER_CUBE:
  985. case GL_SAMPLER_CUBE_SHADOW:
  986. case GL_SAMPLER_CUBE_MAP_ARRAY:
  987. case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW:
  988. return UNIFORM_SAMPLER;
  989. case GL_SAMPLER_BUFFER:
  990. case GL_INT_SAMPLER_BUFFER:
  991. case GL_UNSIGNED_INT_SAMPLER_BUFFER:
  992. return UNIFORM_TEXELBUFFER;
  993. default:
  994. return UNIFORM_UNKNOWN;
  995. }
  996. }
  997. TextureType Shader::getUniformTextureType(GLenum type) const
  998. {
  999. switch (type)
  1000. {
  1001. case GL_SAMPLER_1D:
  1002. case GL_SAMPLER_1D_SHADOW:
  1003. case GL_SAMPLER_1D_ARRAY:
  1004. case GL_SAMPLER_1D_ARRAY_SHADOW:
  1005. // 1D-typed textures are not supported.
  1006. return TEXTURE_MAX_ENUM;
  1007. case GL_SAMPLER_2D:
  1008. case GL_SAMPLER_2D_SHADOW:
  1009. return TEXTURE_2D;
  1010. case GL_SAMPLER_2D_MULTISAMPLE:
  1011. case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
  1012. // Multisample textures are not supported.
  1013. return TEXTURE_MAX_ENUM;
  1014. case GL_SAMPLER_2D_RECT:
  1015. case GL_SAMPLER_2D_RECT_SHADOW:
  1016. // Rectangle textures are not supported.
  1017. return TEXTURE_MAX_ENUM;
  1018. case GL_SAMPLER_2D_ARRAY:
  1019. case GL_SAMPLER_2D_ARRAY_SHADOW:
  1020. return TEXTURE_2D_ARRAY;
  1021. case GL_SAMPLER_3D:
  1022. return TEXTURE_VOLUME;
  1023. case GL_SAMPLER_CUBE:
  1024. case GL_SAMPLER_CUBE_SHADOW:
  1025. return TEXTURE_CUBE;
  1026. case GL_SAMPLER_CUBE_MAP_ARRAY:
  1027. case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW:
  1028. // Cubemap array textures are not supported.
  1029. return TEXTURE_MAX_ENUM;
  1030. default:
  1031. return TEXTURE_MAX_ENUM;
  1032. }
  1033. }
  1034. DataBaseType Shader::getUniformTexelBufferType(GLenum type) const
  1035. {
  1036. switch (type)
  1037. {
  1038. case GL_SAMPLER_BUFFER:
  1039. return DATA_BASETYPE_FLOAT;
  1040. case GL_INT_SAMPLER_BUFFER:
  1041. return DATA_BASETYPE_INT;
  1042. case GL_UNSIGNED_INT_SAMPLER_BUFFER:
  1043. return DATA_BASETYPE_UINT;
  1044. default:
  1045. return DATA_BASETYPE_MAX_ENUM;
  1046. }
  1047. }
  1048. bool Shader::isDepthTextureType(GLenum type) const
  1049. {
  1050. switch (type)
  1051. {
  1052. case GL_SAMPLER_1D_SHADOW:
  1053. case GL_SAMPLER_1D_ARRAY_SHADOW:
  1054. case GL_SAMPLER_2D_SHADOW:
  1055. case GL_SAMPLER_2D_ARRAY_SHADOW:
  1056. case GL_SAMPLER_CUBE_SHADOW:
  1057. case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW:
  1058. return true;
  1059. default:
  1060. return false;
  1061. }
  1062. }
  1063. } // opengl
  1064. } // graphics
  1065. } // love