twgl.js 5.1.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/5.x/twgl.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @license twgl.js 5.1.0 Copyright (c) 2015, Gregg Tavares All Rights Reserved.
2
+ * @license twgl.js 5.2.0 Copyright (c) 2015, Gregg Tavares All Rights Reserved.
3
3
  * Available via the MIT license.
4
4
  * see: http://github.com/greggman/twgl.js for details
5
5
  */
@@ -1549,12 +1549,16 @@ exports.bindTransformFeedbackInfo = bindTransformFeedbackInfo;
1549
1549
  exports.bindUniformBlock = bindUniformBlock;
1550
1550
  exports.createAttributeSetters = createAttributeSetters;
1551
1551
  exports.createProgram = createProgram;
1552
- exports.createProgramAsync = createProgramAsync;
1552
+ exports.createProgramAsync = void 0;
1553
1553
  exports.createProgramFromScripts = createProgramFromScripts;
1554
1554
  exports.createProgramFromSources = createProgramFromSources;
1555
1555
  exports.createProgramInfo = createProgramInfo;
1556
- exports.createProgramInfoAsync = createProgramInfoAsync;
1556
+ exports.createProgramInfoAsync = void 0;
1557
1557
  exports.createProgramInfoFromProgram = createProgramInfoFromProgram;
1558
+ exports.createProgramInfos = createProgramInfos;
1559
+ exports.createProgramInfosAsync = void 0;
1560
+ exports.createPrograms = createPrograms;
1561
+ exports.createProgramsAsync = void 0;
1558
1562
  exports.createTransformFeedback = createTransformFeedback;
1559
1563
  exports.createTransformFeedbackInfo = createTransformFeedbackInfo;
1560
1564
  exports.createUniformBlockInfo = createUniformBlockInfo;
@@ -1572,8 +1576,16 @@ var helper = _interopRequireWildcard(__webpack_require__(/*! ./helper.js */ "./s
1572
1576
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
1573
1577
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
1574
1578
  function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
1579
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
1580
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1581
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
1575
1582
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
1576
1583
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
1584
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
1585
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
1586
+ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
1587
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
1588
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
1577
1589
  function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
1578
1590
  function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
1579
1591
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
@@ -2367,38 +2379,13 @@ function reportError(progOptions, msg) {
2367
2379
  return null;
2368
2380
  }
2369
2381
 
2370
- /**
2371
- * Loads a shader.
2372
- * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
2373
- * @param {string} shaderSource The shader source.
2374
- * @param {number} shaderType The type of shader.
2375
- * @param {module:twgl.ProgramOptions} progOptions
2376
- * @return {WebGLShader} The created shader.
2377
- * @private
2378
- */
2379
- function loadShader(gl, shaderSource, shaderType, progOptions) {
2380
- // Create the shader object
2381
- var shader = gl.createShader(shaderType);
2382
-
2383
- // Load the shader source
2384
- gl.shaderSource(shader, prepShaderSource(shaderSource).shaderSource);
2385
-
2386
- // Compile the shader
2387
- gl.compileShader(shader);
2388
- if (!progOptions.callback && !checkShaderStatus(gl, shaderType, shader, progOptions.errorCallback)) {
2389
- gl.deleteShader(shader);
2390
- return null;
2391
- }
2392
- return shader;
2393
- }
2394
-
2395
2382
  /**
2396
2383
  * Check Shader status
2397
2384
  * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
2398
2385
  * @param {number} shaderType The shader type
2399
2386
  * @param {WebGLShader} shader The shader
2400
2387
  * @param {ErrorCallback} [errFn] function to receive error message.
2401
- * @return {bool} true if shader is ok.
2388
+ * @return {string} errors or empty string
2402
2389
  * @private
2403
2390
  */
2404
2391
  function checkShaderStatus(gl, shaderType, shader, errFn) {
@@ -2411,15 +2398,35 @@ function checkShaderStatus(gl, shaderType, shader, errFn) {
2411
2398
  var _prepShaderSource = prepShaderSource(gl.getShaderSource(shader)),
2412
2399
  lineOffset = _prepShaderSource.lineOffset,
2413
2400
  shaderSource = _prepShaderSource.shaderSource;
2414
- errFn("".concat(addLineNumbersWithError(shaderSource, lastError, lineOffset), "\nError compiling ").concat(utils.glEnumToString(gl, shaderType), ": ").concat(lastError));
2401
+ var _error = "".concat(addLineNumbersWithError(shaderSource, lastError, lineOffset), "\nError compiling ").concat(utils.glEnumToString(gl, shaderType), ": ").concat(lastError);
2402
+ errFn(_error);
2403
+ return _error;
2415
2404
  }
2416
- return compiled;
2405
+ return '';
2417
2406
  }
2418
2407
 
2408
+ /**
2409
+ * @typedef {Object} FullProgramSpec
2410
+ * @property {string[]} shaders the shader source or element ids.
2411
+ * @property {function(string)} [errorCallback] callback for errors
2412
+ * @property {Object.<string,number>|string[]} [attribLocations] a attribute name to location map, or array of attribute names where index = location.
2413
+ * @property {(module:twgl.BufferInfo|Object.<string,module:twgl.AttribInfo>|string[])} [transformFeedbackVaryings] If passed
2414
+ * a BufferInfo will use the attribs names inside. If passed an object of AttribInfos will use the names from that object. Otherwise
2415
+ * you can pass an array of names.
2416
+ * @property {number} [transformFeedbackMode] the mode to pass `gl.transformFeedbackVaryings`. Defaults to `SEPARATE_ATTRIBS`.
2417
+ * @property {ProgramCallback} [callback] callback for async program compilation.
2418
+ * @memberOf module:twgl
2419
+ */
2420
+
2421
+ /**
2422
+ * @typedef {string[]|module:twgl.FullProgramSpec} ProgramSpec
2423
+ * @memberOf module:twgl
2424
+ */
2425
+
2419
2426
  /**
2420
2427
  * @typedef {Object} ProgramOptions
2421
2428
  * @property {function(string)} [errorCallback] callback for errors
2422
- * @property {Object.<string,number>} [attribLocations] a attribute name to location map
2429
+ * @property {Object.<string,number>|string[]} [attribLocations] a attribute name to location map, or array of attribute names where index = location.
2423
2430
  * @property {(module:twgl.BufferInfo|Object.<string,module:twgl.AttribInfo>|string[])} [transformFeedbackVaryings] If passed
2424
2431
  * a BufferInfo will use the attribs names inside. If passed an object of AttribInfos will use the names from that object. Otherwise
2425
2432
  * you can pass an array of names.
@@ -2449,11 +2456,6 @@ function getProgramOptions(opt_attribs, opt_locations, opt_errorCallback) {
2449
2456
  opt_errorCallback = opt_attribs;
2450
2457
  opt_attribs = undefined;
2451
2458
  } else if (opt_attribs && !Array.isArray(opt_attribs)) {
2452
- // If we have an errorCallback we can just return this object
2453
- // Otherwise we need to construct one with default errorCallback
2454
- if (opt_attribs.errorCallback && opt_attribs.errors) {
2455
- return opt_attribs;
2456
- }
2457
2459
  var opt = opt_attribs;
2458
2460
  opt_errorCallback = opt.errorCallback;
2459
2461
  opt_attribs = opt.attribLocations;
@@ -2476,14 +2478,14 @@ function getProgramOptions(opt_attribs, opt_locations, opt_errorCallback) {
2476
2478
  callback: callback,
2477
2479
  errors: errors
2478
2480
  };
2479
- if (opt_attribs) {
2481
+ {
2480
2482
  var attribLocations = {};
2481
2483
  if (Array.isArray(opt_attribs)) {
2482
2484
  opt_attribs.forEach(function (attrib, ndx) {
2483
2485
  attribLocations[attrib] = opt_locations ? opt_locations[ndx] : ndx;
2484
2486
  });
2485
2487
  } else {
2486
- attribLocations = opt_attribs;
2488
+ attribLocations = opt_attribs || {};
2487
2489
  }
2488
2490
  options.attribLocations = attribLocations;
2489
2491
  }
@@ -2498,10 +2500,23 @@ function getShaderTypeFromScriptType(gl, scriptType) {
2498
2500
  }
2499
2501
  return undefined;
2500
2502
  }
2501
- function deleteShaders(gl, shaders) {
2502
- shaders.forEach(function (shader) {
2503
- gl.deleteShader(shader);
2504
- });
2503
+ function deleteProgramAndShaders(gl, program, notThese) {
2504
+ var shaders = gl.getAttachedShaders(program);
2505
+ var _iterator = _createForOfIteratorHelper(shaders),
2506
+ _step;
2507
+ try {
2508
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
2509
+ var shader = _step.value;
2510
+ if (notThese.has(shader)) {
2511
+ gl.deleteShader(shader);
2512
+ }
2513
+ }
2514
+ } catch (err) {
2515
+ _iterator.e(err);
2516
+ } finally {
2517
+ _iterator.f();
2518
+ }
2519
+ gl.deleteProgram(program);
2505
2520
  }
2506
2521
  var wait = function wait() {
2507
2522
  var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
@@ -2509,6 +2524,48 @@ var wait = function wait() {
2509
2524
  return setTimeout(resolve, ms);
2510
2525
  });
2511
2526
  };
2527
+ function createProgramNoCheck(gl, shaders, programOptions) {
2528
+ var program = gl.createProgram();
2529
+ var _getProgramOptions = getProgramOptions(programOptions),
2530
+ attribLocations = _getProgramOptions.attribLocations,
2531
+ transformFeedbackVaryings = _getProgramOptions.transformFeedbackVaryings,
2532
+ transformFeedbackMode = _getProgramOptions.transformFeedbackMode;
2533
+ for (var ndx = 0; ndx < shaders.length; ++ndx) {
2534
+ var shader = shaders[ndx];
2535
+ if (typeof shader === 'string') {
2536
+ var elem = getElementById(shader);
2537
+ var src = elem ? elem.text : shader;
2538
+ var type = gl[defaultShaderType[ndx]];
2539
+ if (elem && elem.type) {
2540
+ type = getShaderTypeFromScriptType(gl, elem.type) || type;
2541
+ }
2542
+ shader = gl.createShader(type);
2543
+ gl.shaderSource(shader, prepShaderSource(src).shaderSource);
2544
+ gl.compileShader(shader);
2545
+ gl.attachShader(program, shader);
2546
+ }
2547
+ }
2548
+ Object.entries(attribLocations).forEach(function (_ref) {
2549
+ var _ref2 = _slicedToArray(_ref, 2),
2550
+ attrib = _ref2[0],
2551
+ loc = _ref2[1];
2552
+ return gl.bindAttribLocation(program, loc, attrib);
2553
+ });
2554
+ {
2555
+ var varyings = transformFeedbackVaryings;
2556
+ if (varyings) {
2557
+ if (varyings.attribs) {
2558
+ varyings = varyings.attribs;
2559
+ }
2560
+ if (!Array.isArray(varyings)) {
2561
+ varyings = Object.keys(varyings);
2562
+ }
2563
+ gl.transformFeedbackVaryings(program, varyings, transformFeedbackMode || SEPARATE_ATTRIBS);
2564
+ }
2565
+ }
2566
+ gl.linkProgram(program);
2567
+ return program;
2568
+ }
2512
2569
 
2513
2570
  /**
2514
2571
  * Creates a program, attaches (and/or compiles) shaders, binds attrib locations, links the
@@ -2534,59 +2591,47 @@ function createProgram(gl, shaders, opt_attribs, opt_locations, opt_errorCallbac
2534
2591
  // This code is really convoluted, because it may or may not be async
2535
2592
  // Maybe it would be better to have a separate function
2536
2593
  var progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);
2537
- var realShaders = [];
2538
- var newShaders = [];
2539
- for (var ndx = 0; ndx < shaders.length; ++ndx) {
2540
- var shader = shaders[ndx];
2541
- if (typeof shader === 'string') {
2542
- var elem = getElementById(shader);
2543
- var src = elem ? elem.text : shader;
2544
- var type = gl[defaultShaderType[ndx]];
2545
- if (elem && elem.type) {
2546
- type = getShaderTypeFromScriptType(gl, elem.type) || type;
2547
- }
2548
- shader = loadShader(gl, src, type, progOptions);
2549
- newShaders.push(shader);
2550
- }
2551
- if (helper.isShader(gl, shader)) {
2552
- realShaders.push(shader);
2594
+ var shaderSet = new Set(shaders);
2595
+ var program = createProgramNoCheck(gl, shaders, progOptions);
2596
+ function hasErrors(gl, program) {
2597
+ var errors = getProgramErrors(gl, program, progOptions.errorCallback);
2598
+ if (errors) {
2599
+ deleteProgramAndShaders(gl, program, shaderSet);
2553
2600
  }
2601
+ return errors;
2554
2602
  }
2555
- if (realShaders.length !== shaders.length) {
2556
- deleteShaders(gl, newShaders);
2557
- return reportError(progOptions, "not enough shaders for program");
2558
- }
2559
- var program = gl.createProgram();
2560
- realShaders.forEach(function (shader) {
2561
- gl.attachShader(program, shader);
2562
- });
2563
- if (progOptions.attribLocations) {
2564
- Object.keys(progOptions.attribLocations).forEach(function (attrib) {
2565
- gl.bindAttribLocation(program, progOptions.attribLocations[attrib], attrib);
2603
+ if (progOptions.callback) {
2604
+ waitForProgramLinkCompletionAsync(gl, program).then(function () {
2605
+ var errors = hasErrors(gl, program);
2606
+ progOptions.callback(errors, errors ? undefined : program);
2566
2607
  });
2608
+ return undefined;
2567
2609
  }
2568
- var varyings = progOptions.transformFeedbackVaryings;
2569
- if (varyings) {
2570
- if (varyings.attribs) {
2571
- varyings = varyings.attribs;
2572
- }
2573
- if (!Array.isArray(varyings)) {
2574
- varyings = Object.keys(varyings);
2575
- }
2576
- gl.transformFeedbackVaryings(program, varyings, progOptions.transformFeedbackMode || SEPARATE_ATTRIBS);
2577
- }
2578
- gl.linkProgram(program);
2579
- if (progOptions.callback) {
2580
- checkForProgramLinkCompletionAsync(gl, program, progOptions);
2581
- return null;
2582
- } else {
2583
- if (!checkProgramStatus(gl, program, progOptions.errorCallback)) {
2584
- gl.deleteProgram(program);
2585
- deleteShaders(gl, newShaders);
2586
- return null;
2610
+ return hasErrors(gl, program) ? undefined : program;
2611
+ }
2612
+
2613
+ /**
2614
+ * This only works because the functions it wraps the first 2 arguments
2615
+ * are gl and any, followed by things that become programOptions
2616
+ * @private
2617
+ */
2618
+ function wrapCallbackFnToAsyncFn(fn) {
2619
+ return function (gl, arg1) {
2620
+ for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
2621
+ args[_key2 - 2] = arguments[_key2];
2587
2622
  }
2588
- return program;
2589
- }
2623
+ return new Promise(function (resolve, reject) {
2624
+ var programOptions = getProgramOptions.apply(void 0, args);
2625
+ programOptions.callback = function (err, program) {
2626
+ if (err) {
2627
+ reject(err);
2628
+ } else {
2629
+ resolve(program);
2630
+ }
2631
+ };
2632
+ fn(gl, arg1, programOptions);
2633
+ });
2634
+ };
2590
2635
  }
2591
2636
 
2592
2637
  /**
@@ -2599,6 +2644,7 @@ function createProgram(gl, shaders, opt_attribs, opt_locations, opt_errorCallbac
2599
2644
  * twgl.createProgramAsync(gl, [vs, fs], opt_attribs, opt_errFunc);
2600
2645
  * twgl.createProgramAsync(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);
2601
2646
  *
2647
+ * @function
2602
2648
  * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
2603
2649
  * @param {WebGLShader[]|string[]} shaders The shaders to attach, or element ids for their source, or strings that contain their source
2604
2650
  * @param {module:twgl.ProgramOptions|string[]|module:twgl.ErrorCallback} [opt_attribs] Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in
@@ -2608,25 +2654,11 @@ function createProgram(gl, shaders, opt_attribs, opt_locations, opt_errorCallbac
2608
2654
  * @return {Promise<WebGLProgram>} The created program
2609
2655
  * @memberOf module:twgl/programs
2610
2656
  */
2611
- function createProgramAsync(gl, shaders) {
2612
- for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
2613
- args[_key2 - 2] = arguments[_key2];
2614
- }
2615
- return new Promise(function (resolve, reject) {
2616
- var programOptions = getProgramOptions.apply(void 0, args);
2617
- programOptions.callback = function (err, program) {
2618
- if (err) {
2619
- reject(err);
2620
- } else {
2621
- resolve(program);
2622
- }
2623
- };
2624
- createProgram(gl, shaders, programOptions);
2625
- });
2626
- }
2657
+ var createProgramAsync = wrapCallbackFnToAsyncFn(createProgram);
2627
2658
 
2628
2659
  /**
2629
2660
  * Same as createProgramInfo but returns a promise
2661
+ * @function
2630
2662
  * @param {WebGLRenderingContext} gl The WebGLRenderingContext
2631
2663
  * to use.
2632
2664
  * @param {string[]} shaderSources Array of sources for the
@@ -2639,45 +2671,15 @@ function createProgramAsync(gl, shaders) {
2639
2671
  * @return {Promise<module:twgl.ProgramInfo>} The created ProgramInfo
2640
2672
  * @memberOf module:twgl/programs
2641
2673
  */
2642
- function createProgramInfoAsync(gl, shaders) {
2643
- for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
2644
- args[_key3 - 2] = arguments[_key3];
2645
- }
2646
- return new Promise(function (resolve, reject) {
2647
- var programOptions = getProgramOptions.apply(void 0, args);
2648
- programOptions.callback = function (err, programInfo) {
2649
- if (err) {
2650
- reject(err);
2651
- } else {
2652
- resolve(programInfo);
2653
- }
2654
- };
2655
- createProgramInfo(gl, shaders, programOptions);
2656
- });
2674
+ exports.createProgramAsync = createProgramAsync;
2675
+ var createProgramInfoAsync = wrapCallbackFnToAsyncFn(createProgramInfo);
2676
+ exports.createProgramInfoAsync = createProgramInfoAsync;
2677
+ function waitForProgramLinkCompletionAsync(_x, _x2) {
2678
+ return _waitForProgramLinkCompletionAsync.apply(this, arguments);
2657
2679
  }
2658
-
2659
- /**
2660
- * Asynchronously wait for program to link.
2661
- * Note: if 'KHR_parallel_shader_compile' extension does not
2662
- * exist then compilation will not be truly async.
2663
- * @param {WebGLRenderingContext} gl The context
2664
- * @param {WebGLProgram} program The program
2665
- * @param {module:twgl.ProgramOptions} progOptions Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in
2666
- * @private
2667
- */
2668
- function checkForProgramLinkCompletionAsync(_x, _x2, _x3) {
2669
- return _checkForProgramLinkCompletionAsync.apply(this, arguments);
2670
- } /**
2671
- * Check a program's link status
2672
- * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
2673
- * @param {WebGLProgram} program Program to check
2674
- * @param {ErrorCallback} [errFn] func for errors
2675
- * @return {bool} true if program is ok
2676
- * @private
2677
- */
2678
- function _checkForProgramLinkCompletionAsync() {
2679
- _checkForProgramLinkCompletionAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(gl, program, progOptions) {
2680
- var ext, checkFn, waitTime, success, err, errFn;
2680
+ function _waitForProgramLinkCompletionAsync() {
2681
+ _waitForProgramLinkCompletionAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(gl, program) {
2682
+ var ext, checkFn, waitTime;
2681
2683
  return _regeneratorRuntime().wrap(function _callee$(_context) {
2682
2684
  while (1) {
2683
2685
  switch (_context.prev = _context.next) {
@@ -2701,27 +2703,54 @@ function _checkForProgramLinkCompletionAsync() {
2701
2703
  break;
2702
2704
  }
2703
2705
  case 7:
2704
- success = checkProgramStatus(gl, program, progOptions.errorCallback);
2705
- err = success ? undefined : progOptions.errors.join('\n');
2706
- if (!success) {
2707
- errFn = progOptions.errorCallback || error;
2708
- errFn(err);
2709
- gl.deleteProgram(program);
2710
- // TODO: delete shaders, but only shaders that were created newly for this
2711
- // program
2712
- program = null;
2713
- }
2714
- progOptions.callback(err, program);
2715
- case 11:
2716
2706
  case "end":
2717
2707
  return _context.stop();
2718
2708
  }
2719
2709
  }
2720
2710
  }, _callee);
2721
2711
  }));
2722
- return _checkForProgramLinkCompletionAsync.apply(this, arguments);
2712
+ return _waitForProgramLinkCompletionAsync.apply(this, arguments);
2723
2713
  }
2724
- function checkProgramStatus(gl, program, errFn) {
2714
+ function waitForAllProgramsLinkCompletionAsync(_x3, _x4) {
2715
+ return _waitForAllProgramsLinkCompletionAsync.apply(this, arguments);
2716
+ } /**
2717
+ * Check a program's link status
2718
+ * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
2719
+ * @param {WebGLProgram} program Program to check
2720
+ * @param {ErrorCallback} [errFn] func for errors
2721
+ * @return {string?} errors if program is failed, else undefined
2722
+ * @private
2723
+ */
2724
+ function _waitForAllProgramsLinkCompletionAsync() {
2725
+ _waitForAllProgramsLinkCompletionAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(gl, programs) {
2726
+ var _i4, _Object$values2, program;
2727
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
2728
+ while (1) {
2729
+ switch (_context2.prev = _context2.next) {
2730
+ case 0:
2731
+ _i4 = 0, _Object$values2 = Object.values(programs);
2732
+ case 1:
2733
+ if (!(_i4 < _Object$values2.length)) {
2734
+ _context2.next = 8;
2735
+ break;
2736
+ }
2737
+ program = _Object$values2[_i4];
2738
+ _context2.next = 5;
2739
+ return waitForProgramLinkCompletionAsync(gl, program);
2740
+ case 5:
2741
+ _i4++;
2742
+ _context2.next = 1;
2743
+ break;
2744
+ case 8:
2745
+ case "end":
2746
+ return _context2.stop();
2747
+ }
2748
+ }
2749
+ }, _callee2);
2750
+ }));
2751
+ return _waitForAllProgramsLinkCompletionAsync.apply(this, arguments);
2752
+ }
2753
+ function getProgramErrors(gl, program, errFn) {
2725
2754
  errFn = errFn || error;
2726
2755
  // Check the link status
2727
2756
  var linked = gl.getProgramParameter(program, LINK_STATUS);
@@ -2729,32 +2758,16 @@ function checkProgramStatus(gl, program, errFn) {
2729
2758
  // something went wrong with the link
2730
2759
  var lastError = gl.getProgramInfoLog(program);
2731
2760
  errFn("Error in program linking: ".concat(lastError));
2761
+ // print any errors from these shaders
2762
+ var shaders = gl.getAttachedShaders(program);
2763
+ var errors = shaders.map(function (shader) {
2764
+ return checkShaderStatus(gl, gl.getShaderParameter(shader, gl.SHADER_TYPE), shader, errFn);
2765
+ });
2766
+ return "".concat(lastError, "\n").concat(errors.filter(function (_) {
2767
+ return _;
2768
+ }).join('\n'));
2732
2769
  }
2733
- return linked;
2734
- }
2735
-
2736
- /**
2737
- * Loads a shader from a script tag.
2738
- * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
2739
- * @param {string} scriptId The id of the script tag.
2740
- * @param {number} [opt_shaderType] The type of shader. If not passed in it will
2741
- * be derived from the type of the script tag.
2742
- * @param {module:twgl.ProgramOptions} [progOptions] callback for errors.
2743
- * @return {WebGLShader?} The created shader or null if error.
2744
- * @private
2745
- */
2746
- function createShaderFromScript(gl, scriptId, opt_shaderType, progOptions) {
2747
- var shaderSource = "";
2748
- var shaderScript = getElementById(scriptId);
2749
- if (!shaderScript) {
2750
- return reportError(progOptions, "unknown script element: ".concat(scriptId));
2751
- }
2752
- shaderSource = shaderScript.text;
2753
- var shaderType = opt_shaderType || getShaderTypeFromScriptType(gl, shaderScript.type);
2754
- if (!shaderType) {
2755
- return reportError(progOptions, 'unknown shader type');
2756
- }
2757
- return loadShader(gl, shaderSource, shaderType, progOptions);
2770
+ return undefined;
2758
2771
  }
2759
2772
 
2760
2773
  /**
@@ -2782,12 +2795,21 @@ function createShaderFromScript(gl, scriptId, opt_shaderType, progOptions) {
2782
2795
  function createProgramFromScripts(gl, shaderScriptIds, opt_attribs, opt_locations, opt_errorCallback) {
2783
2796
  var progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);
2784
2797
  var shaders = [];
2785
- for (var ii = 0; ii < shaderScriptIds.length; ++ii) {
2786
- var shader = createShaderFromScript(gl, shaderScriptIds[ii], gl[defaultShaderType[ii]], progOptions);
2787
- if (!shader) {
2788
- return null;
2798
+ var _iterator2 = _createForOfIteratorHelper(shaderScriptIds),
2799
+ _step2;
2800
+ try {
2801
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2802
+ var scriptId = _step2.value;
2803
+ var shaderScript = getElementById(scriptId);
2804
+ if (!shaderScript) {
2805
+ return reportError(progOptions, "unknown script element: ".concat(scriptId));
2806
+ }
2807
+ shaders.push(shaderScript.text);
2789
2808
  }
2790
- shaders.push(shader);
2809
+ } catch (err) {
2810
+ _iterator2.e(err);
2811
+ } finally {
2812
+ _iterator2.f();
2791
2813
  }
2792
2814
  return createProgram(gl, shaders, progOptions);
2793
2815
  }
@@ -2815,16 +2837,7 @@ function createProgramFromScripts(gl, shaderScriptIds, opt_attribs, opt_location
2815
2837
  * @memberOf module:twgl/programs
2816
2838
  */
2817
2839
  function createProgramFromSources(gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {
2818
- var progOptions = getProgramOptions(opt_attribs, opt_locations, opt_errorCallback);
2819
- var shaders = [];
2820
- for (var ii = 0; ii < shaderSources.length; ++ii) {
2821
- var shader = loadShader(gl, shaderSources[ii], gl[defaultShaderType[ii]], progOptions);
2822
- if (!progOptions.callback && !shader) {
2823
- return null;
2824
- }
2825
- shaders.push(shader);
2826
- }
2827
- return createProgram(gl, shaders, progOptions);
2840
+ return createProgram(gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback);
2828
2841
  }
2829
2842
 
2830
2843
  /**
@@ -3872,11 +3885,7 @@ function createProgramInfo(gl, shaderSources, opt_attribs, opt_locations, opt_er
3872
3885
  var origCallback = progOptions.callback;
3873
3886
  if (origCallback) {
3874
3887
  progOptions.callback = function (err, program) {
3875
- var programInfo;
3876
- if (!err) {
3877
- programInfo = createProgramInfoFromProgram(gl, program);
3878
- }
3879
- origCallback(err, programInfo);
3888
+ origCallback(err, err ? undefined : createProgramInfoFromProgram(gl, program));
3880
3889
  };
3881
3890
  }
3882
3891
  var program = createProgramFromSources(gl, shaderSources, progOptions);
@@ -3885,6 +3894,209 @@ function createProgramInfo(gl, shaderSources, opt_attribs, opt_locations, opt_er
3885
3894
  }
3886
3895
  return createProgramInfoFromProgram(gl, program);
3887
3896
  }
3897
+ function checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions) {
3898
+ // check errors for everything.
3899
+ for (var _i2 = 0, _Object$entries = Object.entries(programs); _i2 < _Object$entries.length; _i2++) {
3900
+ var _Object$entries$_i = _slicedToArray(_Object$entries[_i2], 2),
3901
+ name = _Object$entries$_i[0],
3902
+ program = _Object$entries$_i[1];
3903
+ var options = _objectSpread({}, programOptions);
3904
+ var spec = programSpecs[name];
3905
+ if (!Array.isArray(spec)) {
3906
+ Object.assign(options, spec);
3907
+ }
3908
+ var errors = getProgramErrors(gl, program, options.errorCallback);
3909
+ if (errors) {
3910
+ // delete everything we created
3911
+ for (var _i3 = 0, _Object$values = Object.values(programs); _i3 < _Object$values.length; _i3++) {
3912
+ var _program = _Object$values[_i3];
3913
+ var shaders = gl.getAttachedShaders(_program);
3914
+ gl.deleteProgram(_program);
3915
+ var _iterator3 = _createForOfIteratorHelper(shaders),
3916
+ _step3;
3917
+ try {
3918
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
3919
+ var shader = _step3.value;
3920
+ // Don't delete it if we didn't create it.
3921
+ if (!noDeleteShadersSet.has(shader)) {
3922
+ gl.deleteShader(shader);
3923
+ }
3924
+ }
3925
+ } catch (err) {
3926
+ _iterator3.e(err);
3927
+ } finally {
3928
+ _iterator3.f();
3929
+ }
3930
+ }
3931
+ return errors;
3932
+ }
3933
+ }
3934
+ return undefined;
3935
+ }
3936
+
3937
+ /**
3938
+ * Creates multiple programs
3939
+ *
3940
+ * Note: the reason this function exists is because the fastest way to create multiple
3941
+ * programs in WebGL is to create and compile all shaders and link all programs and only
3942
+ * afterwards check if they succeeded. In that way, giving all your shaders
3943
+ *
3944
+ * @see {@link module:twgl.createProgram}
3945
+ *
3946
+ * Example:
3947
+ *
3948
+ * const programs = twgl.createPrograms(gl, {
3949
+ * lambert: [lambertVS, lambertFS],
3950
+ * phong: [phongVS, phoneFS],
3951
+ * particles: {
3952
+ * shaders: [particlesVS, particlesFS],
3953
+ * transformFeedbackVaryings: ['position', 'velocity'],
3954
+ * },
3955
+ * });
3956
+ *
3957
+ * @param {WebGLRenderingContext} gl the WebGLRenderingContext
3958
+ * @param {Object.<string, module:twgl.ProgramSpec>} programSpecs An object of ProgramSpecs, one per program.
3959
+ * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs
3960
+ * @return {Object.<string, WebGLProgram>?} the created programInfos by name
3961
+ */
3962
+ function createPrograms(gl, programSpecs) {
3963
+ var programOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
3964
+ // Remember existing shaders so that if there is an error we don't delete them
3965
+ var noDeleteShadersSet = new Set();
3966
+
3967
+ // compile and link everything
3968
+ var programs = Object.fromEntries(Object.entries(programSpecs).map(function (_ref3) {
3969
+ var _ref4 = _slicedToArray(_ref3, 2),
3970
+ name = _ref4[0],
3971
+ spec = _ref4[1];
3972
+ var options = _objectSpread({}, programOptions);
3973
+ var shaders = Array.isArray(spec) ? spec : spec.shaders;
3974
+ if (!Array.isArray(spec)) {
3975
+ Object.assign(options, spec);
3976
+ }
3977
+ shaders.forEach(noDeleteShadersSet.add, noDeleteShadersSet);
3978
+ return [name, createProgramNoCheck(gl, shaders, options)];
3979
+ }));
3980
+ if (programOptions.callback) {
3981
+ waitForAllProgramsLinkCompletionAsync(gl, programs).then(function () {
3982
+ var errors = checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions);
3983
+ programOptions.callback(errors, errors ? undefined : programs);
3984
+ });
3985
+ return undefined;
3986
+ }
3987
+ var errors = checkAllPrograms(gl, programs, programSpecs, noDeleteShadersSet, programOptions);
3988
+ return errors ? undefined : programs;
3989
+ }
3990
+
3991
+ /**
3992
+ * Creates multiple programInfos
3993
+ *
3994
+ * Note: the reason this function exists is because the fastest way to create multiple
3995
+ * programs in WebGL is to create and compile all shaders and link all programs and only
3996
+ * afterwards check if they succeeded. In that way, giving all your shaders
3997
+ *
3998
+ * @see {@link module:twgl.createProgramInfo}
3999
+ *
4000
+ * Examples:
4001
+ *
4002
+ * const programInfos = twgl.createProgramInfos(gl, {
4003
+ * lambert: [lambertVS, lambertFS],
4004
+ * phong: [phongVS, phoneFS],
4005
+ * particles: {
4006
+ * shaders: [particlesVS, particlesFS],
4007
+ * transformFeedbackVaryings: ['position', 'velocity'],
4008
+ * },
4009
+ * });
4010
+ *
4011
+ * or
4012
+ *
4013
+ * const {lambert, phong, particles} = twgl.createProgramInfos(gl, {
4014
+ * lambert: [lambertVS, lambertFS],
4015
+ * phong: [phongVS, phoneFS],
4016
+ * particles: {
4017
+ * shaders: [particlesVS, particlesFS],
4018
+ * transformFeedbackVaryings: ['position', 'velocity'],
4019
+ * },
4020
+ * });
4021
+ *
4022
+ *
4023
+ * @param {WebGLRenderingContext} gl the WebGLRenderingContext
4024
+ * @param {Object.<string, module:twgl.ProgramSpec>} programSpecs An object of ProgramSpecs, one per program.
4025
+ * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs
4026
+ * @return {Object.<string, module:twgl.ProgramInfo>?} the created programInfos by name
4027
+ */
4028
+ function createProgramInfos(gl, programSpecs, programOptions) {
4029
+ programOptions = getProgramOptions(programOptions);
4030
+ function createProgramInfosForPrograms(gl, programs) {
4031
+ return Object.fromEntries(Object.entries(programs).map(function (_ref5) {
4032
+ var _ref6 = _slicedToArray(_ref5, 2),
4033
+ name = _ref6[0],
4034
+ program = _ref6[1];
4035
+ return [name, createProgramInfoFromProgram(gl, program)];
4036
+ }));
4037
+ }
4038
+ var origCallback = programOptions.callback;
4039
+ if (origCallback) {
4040
+ programOptions.callback = function (err, programs) {
4041
+ origCallback(err, err ? undefined : createProgramInfosForPrograms(gl, programs));
4042
+ };
4043
+ }
4044
+ var programs = createPrograms(gl, programSpecs, programOptions);
4045
+ if (origCallback || !programs) {
4046
+ return undefined;
4047
+ }
4048
+ return createProgramInfosForPrograms(gl, programs);
4049
+ }
4050
+
4051
+ /**
4052
+ * Creates multiple programs asynchronously
4053
+ *
4054
+ * @see {@link module:twgl.createProgramAsync}
4055
+ *
4056
+ * Example:
4057
+ *
4058
+ * const programs = await twgl.createProgramsAsync(gl, {
4059
+ * lambert: [lambertVS, lambertFS],
4060
+ * phong: [phongVS, phoneFS],
4061
+ * particles: {
4062
+ * shaders: [particlesVS, particlesFS],
4063
+ * transformFeedbackVaryings: ['position', 'velocity'],
4064
+ * },
4065
+ * });
4066
+ *
4067
+ * @function
4068
+ * @param {WebGLRenderingContext} gl the WebGLRenderingContext
4069
+ * @param {Object.<string, module:twgl.ProgramSpec>} programSpecs An object of ProgramSpecs, one per program.
4070
+ * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs
4071
+ * @return {Object.<string, WebGLProgram>?} the created programInfos by name
4072
+ */
4073
+ var createProgramsAsync = wrapCallbackFnToAsyncFn(createPrograms);
4074
+
4075
+ /**
4076
+ * Creates multiple programInfos asynchronously
4077
+ *
4078
+ * @see {@link module:twgl.createProgramInfoAsync}
4079
+ *
4080
+ * Example:
4081
+ *
4082
+ * const programInfos = await twgl.createProgramInfosAsync(gl, {
4083
+ * lambert: [lambertVS, lambertFS],
4084
+ * phong: [phongVS, phoneFS],
4085
+ * particles: {
4086
+ * shaders: [particlesVS, particlesFS],
4087
+ * transformFeedbackVaryings: ['position', 'velocity'],
4088
+ * },
4089
+ * });
4090
+ *
4091
+ * @function
4092
+ * @param {WebGLRenderingContext} gl the WebGLRenderingContext
4093
+ * @param {Object.<string, module:twgl.ProgramSpec>} programSpecs An object of ProgramSpecs, one per program.
4094
+ * @param {module:twgl.ProgramOptions} [programOptions] options to apply to all programs
4095
+ * @return {Promise<Object.<string, module:twgl.ProgramInfo>>} the created programInfos by name
4096
+ */
4097
+ exports.createProgramsAsync = createProgramsAsync;
4098
+ var createProgramInfosAsync = wrapCallbackFnToAsyncFn(createProgramInfos);
4099
+ exports.createProgramInfosAsync = createProgramInfosAsync;
3888
4100
 
3889
4101
  /***/ }),
3890
4102