Shader.cpp 32 KB

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