CustomShader.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. import Check from "../../Core/Check.js";
  2. import defaultValue from "../../Core/defaultValue.js";
  3. import defined from "../../Core/defined.js";
  4. import destroyObject from "../../Core/destroyObject.js";
  5. import DeveloperError from "../../Core/DeveloperError.js";
  6. import CustomShaderMode from "./CustomShaderMode.js";
  7. import UniformType from "./UniformType.js";
  8. import TextureManager from "./TextureManager.js";
  9. /**
  10. * An object describing a uniform, its type, and an initial value
  11. *
  12. * @typedef {Object} UniformSpecifier
  13. * @property {UniformType} type The Glsl type of the uniform.
  14. * @property {Boolean|Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4|TextureUniform} value The initial value of the uniform
  15. *
  16. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  17. */
  18. /**
  19. * A set of variables parsed from the user-defined shader code. These can be
  20. * used for optimizations when generating the overall shader. Though they are
  21. * represented as JS objects, the intended use is like a set, so only the
  22. * existence of keys matter. The values will always be <code>true</code> if
  23. * defined. This data structure is used because:
  24. * <ul>
  25. * <li>We cannot yet use ES6 Set objects</li>
  26. * <li>Using a dictionary automatically de-duplicates variable names</li>
  27. * <li>Queries such as <code>variableSet.hasOwnProperty("position")</code> are straightforward</li>
  28. * </ul>
  29. * @typedef {Object<String, Boolean>} VariableSet
  30. * @private
  31. */
  32. /**
  33. * Variable sets parsed from the user-defined vertex shader text.
  34. * @typedef {Object} VertexVariableSets
  35. * @property {VariableSet} attributeSet A set of all unique attributes used in the vertex shader via the <code>vsInput.attributes</code> struct.
  36. * @property {VariableSet} featureIdSet A set of all unique feature ID sets used in the vertex shader via the <code>vsInput.featureIds</code> struct.
  37. * @property {VariableSet} metadataSet A set of all unique metadata properties used in the vertex shader via the <code>vsInput.metadata</code> struct.
  38. * @private
  39. */
  40. /**
  41. * Variable sets parsed from the user-defined fragment shader text.
  42. * @typedef {Object} FragmentVariableSets
  43. * @property {VariableSet} attributeSet A set of all unique attributes used in the fragment shader via the <code>fsInput.attributes</code> struct
  44. * @property {VariableSet} featureIdSet A set of all unique feature ID sets used in the fragment shader via the <code>fsInput.featureIds</code> struct.
  45. * @property {VariableSet} metadataSet A set of all unique metadata properties used in the fragment shader via the <code>fsInput.metadata</code> struct.
  46. * @property {VariableSet} materialSet A set of all material variables such as diffuse, specular or alpha that are used in the fragment shader via the <code>material</code> struct.
  47. * @private
  48. */
  49. /**
  50. * A user defined GLSL shader used with {@link ModelExperimental} as well
  51. * as {@link Cesium3DTileset}.
  52. * <p>
  53. * If texture uniforms are used, additional resource management must be done:
  54. * </p>
  55. * <ul>
  56. * <li>
  57. * The <code>update</code> function must be called each frame. When a
  58. * custom shader is passed to a {@link ModelExperimental} or a
  59. * {@link Cesium3DTileset}, this step is handled automaticaly
  60. * </li>
  61. * <li>
  62. * {@link CustomShader#destroy} must be called when the custom shader is
  63. * no longer needed to clean up GPU resources properly. The application
  64. * is responsible for calling this method.
  65. * </li>
  66. * </ul>
  67. * <p>
  68. * To enable the use of {@link ModelExperimental} in {@link Cesium3DTileset}, set {@link ExperimentalFeatures.enableModelExperimental} to <code>true</code> or tileset.enableModelExperimental to <code>true</code>.
  69. * </p>
  70. * <p>
  71. * See the {@link https://github.com/CesiumGS/cesium/tree/main/Documentation/CustomShaderGuide|Custom Shader Guide} for more detailed documentation.
  72. * </p>
  73. *
  74. * @param {Object} options An object with the following options
  75. * @param {CustomShaderMode} [options.mode=CustomShaderMode.MODIFY_MATERIAL] The custom shader mode, which determines how the custom shader code is inserted into the fragment shader.
  76. * @param {LightingModel} [options.lightingModel] The lighting model (e.g. PBR or unlit). If present, this overrides the default lighting for the model.
  77. * @param {Boolean} [options.isTranslucent=false] If set, the model will be rendered as translucent. This overrides the default settings for the model.
  78. * @param {Object.<String, UniformSpecifier>} [options.uniforms] A dictionary for user-defined uniforms. The key is the uniform name that will appear in the GLSL code. The value is an object that describes the uniform type and initial value
  79. * @param {Object.<String, VaryingType>} [options.varyings] A dictionary for declaring additional GLSL varyings used in the shader. The key is the varying name that will appear in the GLSL code. The value is the data type of the varying. For each varying, the declaration will be added to the top of the shader automatically. The caller is responsible for assigning a value in the vertex shader and using the value in the fragment shader.
  80. * @param {String} [options.vertexShaderText] The custom vertex shader as a string of GLSL code. It must include a GLSL function called vertexMain. See the example for the expected signature. If not specified, the custom vertex shader step will be skipped in the computed vertex shader.
  81. * @param {String} [options.fragmentShaderText] The custom fragment shader as a string of GLSL code. It must include a GLSL function called fragmentMain. See the example for the expected signature. If not specified, the custom fragment shader step will be skipped in the computed fragment shader.
  82. *
  83. * @alias CustomShader
  84. * @constructor
  85. *
  86. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  87. *
  88. * @example
  89. * const customShader = new CustomShader({
  90. * uniforms: {
  91. * u_colorIndex: {
  92. * type: Cesium.UniformType.FLOAT,
  93. * value: 1.0
  94. * },
  95. * u_normalMap: {
  96. * type: Cesium.UniformType.SAMPLER_2D,
  97. * value: new Cesium.TextureUniform({
  98. * url: "http://example.com/normal.png"
  99. * })
  100. * }
  101. * },
  102. * varyings: {
  103. * v_selectedColor: Cesium.VaryingType.VEC3
  104. * },
  105. * vertexShaderText: `
  106. * void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
  107. * v_selectedColor = mix(vsInput.attributes.color_0, vsInput.attributes.color_1, u_colorIndex);
  108. * vsOutput.positionMC += 0.1 * vsInput.attributes.normal;
  109. * }
  110. * `,
  111. * fragmentShaderText: `
  112. * void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
  113. * material.normal = texture2D(u_normalMap, fsInput.attributes.texCoord_0);
  114. * material.diffuse = v_selectedColor;
  115. * }
  116. * `
  117. * });
  118. */
  119. export default function CustomShader(options) {
  120. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  121. /**
  122. * A value determining how the custom shader interacts with the overall
  123. * fragment shader. This is used by {@link CustomShaderPipelineStage}
  124. *
  125. * @type {CustomShaderMode}
  126. * @readonly
  127. */
  128. this.mode = defaultValue(options.mode, CustomShaderMode.MODIFY_MATERIAL);
  129. /**
  130. * The lighting model to use when using the custom shader.
  131. * This is used by {@link CustomShaderPipelineStage}
  132. *
  133. * @type {LightingModel}
  134. * @readonly
  135. */
  136. this.lightingModel = options.lightingModel;
  137. /**
  138. * Additional uniforms as declared by the user.
  139. *
  140. * @type {Object.<String, UniformSpecifier>}
  141. * @readonly
  142. */
  143. this.uniforms = defaultValue(options.uniforms, defaultValue.EMPTY_OBJECT);
  144. /**
  145. * Additional varyings as declared by the user.
  146. * This is used by {@link CustomShaderPipelineStage}
  147. *
  148. * @type {Object.<String, VaryingType>}
  149. * @readonly
  150. */
  151. this.varyings = defaultValue(options.varyings, defaultValue.EMPTY_OBJECT);
  152. /**
  153. * The user-defined GLSL code for the vertex shader
  154. *
  155. * @type {String}
  156. * @readonly
  157. */
  158. this.vertexShaderText = options.vertexShaderText;
  159. /**
  160. * The user-defined GLSL code for the fragment shader
  161. *
  162. * @type {String}
  163. * @readonly
  164. */
  165. this.fragmentShaderText = options.fragmentShaderText;
  166. /**
  167. * Whether the shader should be rendered as translucent
  168. *
  169. * @type {Boolean}
  170. * @readonly
  171. */
  172. this.isTranslucent = defaultValue(options.isTranslucent, false);
  173. /**
  174. * texture uniforms require some asynchronous processing. This is delegated
  175. * to a texture manager.
  176. *
  177. * @type {TextureManager}
  178. * @readonly
  179. * @private
  180. */
  181. this._textureManager = new TextureManager();
  182. /**
  183. * The default texture (from the {@link Context}) to use while textures
  184. * are loading
  185. *
  186. * @type {Texture}
  187. * @readonly
  188. * @private
  189. */
  190. this._defaultTexture = undefined;
  191. /**
  192. * The map of uniform names to a function that returns a value. This map
  193. * is combined with the overall uniform map used by the {@link DrawCommand}
  194. *
  195. * @type {Object.<String, Function>}
  196. * @readonly
  197. * @private
  198. */
  199. this.uniformMap = buildUniformMap(this);
  200. /**
  201. * A collection of variables used in <code>vertexShaderText</code>. This
  202. * is used only for optimizations in {@link CustomShaderPipelineStage}.
  203. * @type {VertexVariableSets}
  204. * @private
  205. */
  206. this.usedVariablesVertex = {
  207. attributeSet: {},
  208. featureIdSet: {},
  209. metadataSet: {},
  210. };
  211. /**
  212. * A collection of variables used in <code>fragmentShaderText</code>. This
  213. * is used only for optimizations in {@link CustomShaderPipelineStage}.
  214. * @type {FragmentVariableSets}
  215. * @private
  216. */
  217. this.usedVariablesFragment = {
  218. attributeSet: {},
  219. featureIdSet: {},
  220. metadataSet: {},
  221. materialSet: {},
  222. };
  223. findUsedVariables(this);
  224. validateBuiltinVariables(this);
  225. }
  226. function buildUniformMap(customShader) {
  227. const uniforms = customShader.uniforms;
  228. const uniformMap = {};
  229. for (const uniformName in uniforms) {
  230. if (uniforms.hasOwnProperty(uniformName)) {
  231. const uniform = uniforms[uniformName];
  232. const type = uniform.type;
  233. //>>includeStart('debug', pragmas.debug);
  234. if (type === UniformType.SAMPLER_CUBE) {
  235. throw new DeveloperError(
  236. "CustomShader does not support samplerCube uniforms"
  237. );
  238. }
  239. //>>includeEnd('debug');
  240. if (type === UniformType.SAMPLER_2D) {
  241. customShader._textureManager.loadTexture2D(uniformName, uniform.value);
  242. uniformMap[uniformName] = createUniformTexture2DFunction(
  243. customShader,
  244. uniformName
  245. );
  246. } else {
  247. uniformMap[uniformName] = createUniformFunction(
  248. customShader,
  249. uniformName
  250. );
  251. }
  252. }
  253. }
  254. return uniformMap;
  255. }
  256. function createUniformTexture2DFunction(customShader, uniformName) {
  257. return function () {
  258. return defaultValue(
  259. customShader._textureManager.getTexture(uniformName),
  260. customShader._defaultTexture
  261. );
  262. };
  263. }
  264. function createUniformFunction(customShader, uniformName) {
  265. return function () {
  266. return customShader.uniforms[uniformName].value;
  267. };
  268. }
  269. function getVariables(shaderText, regex, outputSet) {
  270. let match;
  271. while ((match = regex.exec(shaderText)) !== null) {
  272. const variableName = match[1];
  273. // Using a dictionary like a set. The value doesn't
  274. // matter, as this will only be used for queries such as
  275. // if (set.hasOwnProperty(variableName)) { ... }
  276. outputSet[variableName] = true;
  277. }
  278. }
  279. function findUsedVariables(customShader) {
  280. const attributeRegex = /[vf]sInput\.attributes\.(\w+)/g;
  281. const featureIdRegex = /[vf]sInput\.featureIds\.(\w+)/g;
  282. const metadataRegex = /[vf]sInput\.metadata.(\w+)/g;
  283. let attributeSet;
  284. const vertexShaderText = customShader.vertexShaderText;
  285. if (defined(vertexShaderText)) {
  286. attributeSet = customShader.usedVariablesVertex.attributeSet;
  287. getVariables(vertexShaderText, attributeRegex, attributeSet);
  288. attributeSet = customShader.usedVariablesVertex.featureIdSet;
  289. getVariables(vertexShaderText, featureIdRegex, attributeSet);
  290. attributeSet = customShader.usedVariablesVertex.metadataSet;
  291. getVariables(vertexShaderText, metadataRegex, attributeSet);
  292. }
  293. const fragmentShaderText = customShader.fragmentShaderText;
  294. if (defined(fragmentShaderText)) {
  295. attributeSet = customShader.usedVariablesFragment.attributeSet;
  296. getVariables(fragmentShaderText, attributeRegex, attributeSet);
  297. attributeSet = customShader.usedVariablesFragment.featureIdSet;
  298. getVariables(fragmentShaderText, featureIdRegex, attributeSet);
  299. attributeSet = customShader.usedVariablesFragment.metadataSet;
  300. getVariables(fragmentShaderText, metadataRegex, attributeSet);
  301. const materialRegex = /material\.(\w+)/g;
  302. const materialSet = customShader.usedVariablesFragment.materialSet;
  303. getVariables(fragmentShaderText, materialRegex, materialSet);
  304. }
  305. }
  306. function expandCoordinateAbbreviations(variableName) {
  307. const modelCoordinatesRegex = /^.*MC$/;
  308. const worldCoordinatesRegex = /^.*WC$/;
  309. const eyeCoordinatesRegex = /^.*EC$/;
  310. if (modelCoordinatesRegex.test(variableName)) {
  311. return `${variableName} (model coordinates)`;
  312. }
  313. if (worldCoordinatesRegex.test(variableName)) {
  314. return `${variableName} (Cartesian world coordinates)`;
  315. }
  316. if (eyeCoordinatesRegex.test(variableName)) {
  317. return `${variableName} (eye coordinates)`;
  318. }
  319. return variableName;
  320. }
  321. function validateVariableUsage(
  322. variableSet,
  323. incorrectVariable,
  324. correctVariable,
  325. vertexOrFragment
  326. ) {
  327. if (variableSet.hasOwnProperty(incorrectVariable)) {
  328. const message = `${expandCoordinateAbbreviations(
  329. incorrectVariable
  330. )} is not available in the ${vertexOrFragment} shader. Did you mean ${expandCoordinateAbbreviations(
  331. correctVariable
  332. )} instead?`;
  333. throw new DeveloperError(message);
  334. }
  335. }
  336. function validateBuiltinVariables(customShader) {
  337. const attributesVS = customShader.usedVariablesVertex.attributeSet;
  338. // names without MC/WC/EC are ambiguous
  339. validateVariableUsage(attributesVS, "position", "positionMC", "vertex");
  340. validateVariableUsage(attributesVS, "normal", "normalMC", "vertex");
  341. validateVariableUsage(attributesVS, "tangent", "tangentMC", "vertex");
  342. validateVariableUsage(attributesVS, "bitangent", "bitangentMC", "vertex");
  343. // world and eye coordinate positions are only available in the fragment shader.
  344. validateVariableUsage(attributesVS, "positionWC", "positionMC", "vertex");
  345. validateVariableUsage(attributesVS, "positionEC", "positionMC", "vertex");
  346. // normal, tangent and bitangent are in model coordinates in the vertex shader
  347. validateVariableUsage(attributesVS, "normalEC", "normalMC", "vertex");
  348. validateVariableUsage(attributesVS, "tangentEC", "tangentMC", "vertex");
  349. validateVariableUsage(attributesVS, "bitangentEC", "bitangentMC", "vertex");
  350. const attributesFS = customShader.usedVariablesFragment.attributeSet;
  351. // names without MC/WC/EC are ambiguous
  352. validateVariableUsage(attributesFS, "position", "positionEC", "fragment");
  353. validateVariableUsage(attributesFS, "normal", "normalEC", "fragment");
  354. validateVariableUsage(attributesFS, "tangent", "tangentEC", "fragment");
  355. validateVariableUsage(attributesFS, "bitangent", "bitangentEC", "fragment");
  356. // normal, tangent, and bitangent are in eye coordinates in the fragment
  357. // shader.
  358. validateVariableUsage(attributesFS, "normalMC", "normalEC", "fragment");
  359. validateVariableUsage(attributesFS, "tangentMC", "tangentEC", "fragment");
  360. validateVariableUsage(attributesFS, "bitangentMC", "bitangentEC", "fragment");
  361. }
  362. /**
  363. * Update the value of a uniform declared in the shader
  364. * @param {String} uniformName The GLSL name of the uniform. This must match one of the uniforms declared in the constructor
  365. * @param {Boolean|Number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4|String|Resource} value The new value of the uniform.
  366. */
  367. CustomShader.prototype.setUniform = function (uniformName, value) {
  368. //>>includeStart('debug', pragmas.debug);
  369. Check.typeOf.string("uniformName", uniformName);
  370. Check.defined("value", value);
  371. if (!defined(this.uniforms[uniformName])) {
  372. throw new DeveloperError(
  373. `Uniform ${uniformName} must be declared in the CustomShader constructor.`
  374. );
  375. }
  376. //>>includeEnd('debug');
  377. const uniform = this.uniforms[uniformName];
  378. if (uniform.type === UniformType.SAMPLER_2D) {
  379. // Textures are loaded asynchronously
  380. this._textureManager.loadTexture2D(uniformName, value);
  381. } else if (defined(value.clone)) {
  382. // clone Cartesian and Matrix types.
  383. uniform.value = value.clone(uniform.value);
  384. } else {
  385. uniform.value = value;
  386. }
  387. };
  388. CustomShader.prototype.update = function (frameState) {
  389. this._defaultTexture = frameState.context.defaultTexture;
  390. this._textureManager.update(frameState);
  391. };
  392. /**
  393. * Returns true if this object was destroyed; otherwise, false.
  394. * <br /><br />
  395. * If this object was destroyed, it should not be used; calling any function other than
  396. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  397. *
  398. * @returns {Boolean} True if this object was destroyed; otherwise, false.
  399. *
  400. * @see CustomShader#destroy
  401. * @private
  402. */
  403. CustomShader.prototype.isDestroyed = function () {
  404. return false;
  405. };
  406. /**
  407. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  408. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  409. * <br /><br />
  410. * Once an object is destroyed, it should not be used; calling any function other than
  411. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  412. * assign the return value (<code>undefined</code>) to the object as done in the example.
  413. *
  414. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  415. *
  416. * @example
  417. * customShader = customShader && customShader.destroy();
  418. *
  419. * @see CustomShader#isDestroyed
  420. * @private
  421. */
  422. CustomShader.prototype.destroy = function () {
  423. this._textureManager = this._textureManager && this._textureManager.destroy();
  424. destroyObject(this);
  425. };