ShaderFunction.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * A utility for dynamically-generating a GLSL function
  3. *
  4. * @alias ShaderFunction
  5. * @constructor
  6. *
  7. * @see {@link ShaderBuilder}
  8. * @param {String} signature The full signature of the function as it will appear in the shader. Do not include the curly braces.
  9. * @example
  10. * // generate the following function
  11. * //
  12. * // void assignVaryings(vec3 position)
  13. * // {
  14. * // v_positionEC = (czm_modelView * vec4(a_position, 1.0)).xyz;
  15. * // v_texCoord = a_texCoord;
  16. * // }
  17. * const signature = "void assignVaryings(vec3 position)";
  18. * const func = new ShaderFunction(signature);
  19. * func.addLine("v_positionEC = (czm_modelView * vec4(a_position, 1.0)).xyz;");
  20. * func.addLine("v_texCoord = a_texCoord;");
  21. * const generatedLines = func.generateGlslLines();
  22. *
  23. * @private
  24. */
  25. export default function ShaderFunction(signature) {
  26. this.signature = signature;
  27. this.body = [];
  28. }
  29. /**
  30. * Add an array of lines to the body of the function
  31. * @param {String[]} lines An array of lines of GLSL code to add to the function body. Do not include any preceding or ending whitespace, but do include the semicolon for each line.
  32. */
  33. ShaderFunction.prototype.addLines = function (lines) {
  34. const paddedLines = lines.map(function (line) {
  35. return ` ${line}`;
  36. });
  37. Array.prototype.push.apply(this.body, paddedLines);
  38. };
  39. /**
  40. * Generate lines of GLSL code for use with {@link ShaderBuilder}
  41. * @return {String[]}
  42. */
  43. ShaderFunction.prototype.generateGlslLines = function () {
  44. return [].concat(this.signature, "{", this.body, "}");
  45. };