Shader.cpp 30 KB

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