vap.js 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Vap = {}));
  5. }(this, (function (exports) { 'use strict';
  6. function _arrayLikeToArray(arr, len) {
  7. if (len == null || len > arr.length) len = arr.length;
  8. for (var i = 0, arr2 = new Array(len); i < len; i++) {
  9. arr2[i] = arr[i];
  10. }
  11. return arr2;
  12. }
  13. var arrayLikeToArray = _arrayLikeToArray;
  14. function _arrayWithoutHoles(arr) {
  15. if (Array.isArray(arr)) return arrayLikeToArray(arr);
  16. }
  17. var arrayWithoutHoles = _arrayWithoutHoles;
  18. function _iterableToArray(iter) {
  19. if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
  20. }
  21. var iterableToArray = _iterableToArray;
  22. function _unsupportedIterableToArray(o, minLen) {
  23. if (!o) return;
  24. if (typeof o === "string") return arrayLikeToArray(o, minLen);
  25. var n = Object.prototype.toString.call(o).slice(8, -1);
  26. if (n === "Object" && o.constructor) n = o.constructor.name;
  27. if (n === "Map" || n === "Set") return Array.from(o);
  28. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
  29. }
  30. var unsupportedIterableToArray = _unsupportedIterableToArray;
  31. function _nonIterableSpread() {
  32. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  33. }
  34. var nonIterableSpread = _nonIterableSpread;
  35. function _toConsumableArray(arr) {
  36. return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
  37. }
  38. var toConsumableArray = _toConsumableArray;
  39. function _arrayWithHoles(arr) {
  40. if (Array.isArray(arr)) return arr;
  41. }
  42. var arrayWithHoles = _arrayWithHoles;
  43. function _iterableToArrayLimit(arr, i) {
  44. if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
  45. var _arr = [];
  46. var _n = true;
  47. var _d = false;
  48. var _e = undefined;
  49. try {
  50. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  51. _arr.push(_s.value);
  52. if (i && _arr.length === i) break;
  53. }
  54. } catch (err) {
  55. _d = true;
  56. _e = err;
  57. } finally {
  58. try {
  59. if (!_n && _i["return"] != null) _i["return"]();
  60. } finally {
  61. if (_d) throw _e;
  62. }
  63. }
  64. return _arr;
  65. }
  66. var iterableToArrayLimit = _iterableToArrayLimit;
  67. function _nonIterableRest() {
  68. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  69. }
  70. var nonIterableRest = _nonIterableRest;
  71. function _slicedToArray(arr, i) {
  72. return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
  73. }
  74. var slicedToArray = _slicedToArray;
  75. function _classCallCheck(instance, Constructor) {
  76. if (!(instance instanceof Constructor)) {
  77. throw new TypeError("Cannot call a class as a function");
  78. }
  79. }
  80. var classCallCheck = _classCallCheck;
  81. function _defineProperties(target, props) {
  82. for (var i = 0; i < props.length; i++) {
  83. var descriptor = props[i];
  84. descriptor.enumerable = descriptor.enumerable || false;
  85. descriptor.configurable = true;
  86. if ("value" in descriptor) descriptor.writable = true;
  87. Object.defineProperty(target, descriptor.key, descriptor);
  88. }
  89. }
  90. function _createClass(Constructor, protoProps, staticProps) {
  91. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  92. if (staticProps) _defineProperties(Constructor, staticProps);
  93. return Constructor;
  94. }
  95. var createClass = _createClass;
  96. function createCommonjsModule(fn, module) {
  97. return module = { exports: {} }, fn(module, module.exports), module.exports;
  98. }
  99. var getPrototypeOf = createCommonjsModule(function (module) {
  100. function _getPrototypeOf(o) {
  101. module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  102. return o.__proto__ || Object.getPrototypeOf(o);
  103. };
  104. return _getPrototypeOf(o);
  105. }
  106. module.exports = _getPrototypeOf;
  107. });
  108. function _superPropBase(object, property) {
  109. while (!Object.prototype.hasOwnProperty.call(object, property)) {
  110. object = getPrototypeOf(object);
  111. if (object === null) break;
  112. }
  113. return object;
  114. }
  115. var superPropBase = _superPropBase;
  116. var get = createCommonjsModule(function (module) {
  117. function _get(target, property, receiver) {
  118. if (typeof Reflect !== "undefined" && Reflect.get) {
  119. module.exports = _get = Reflect.get;
  120. } else {
  121. module.exports = _get = function _get(target, property, receiver) {
  122. var base = superPropBase(target, property);
  123. if (!base) return;
  124. var desc = Object.getOwnPropertyDescriptor(base, property);
  125. if (desc.get) {
  126. return desc.get.call(receiver);
  127. }
  128. return desc.value;
  129. };
  130. }
  131. return _get(target, property, receiver || target);
  132. }
  133. module.exports = _get;
  134. });
  135. var setPrototypeOf = createCommonjsModule(function (module) {
  136. function _setPrototypeOf(o, p) {
  137. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  138. o.__proto__ = p;
  139. return o;
  140. };
  141. return _setPrototypeOf(o, p);
  142. }
  143. module.exports = _setPrototypeOf;
  144. });
  145. function _inherits(subClass, superClass) {
  146. if (typeof superClass !== "function" && superClass !== null) {
  147. throw new TypeError("Super expression must either be null or a function");
  148. }
  149. subClass.prototype = Object.create(superClass && superClass.prototype, {
  150. constructor: {
  151. value: subClass,
  152. writable: true,
  153. configurable: true
  154. }
  155. });
  156. if (superClass) setPrototypeOf(subClass, superClass);
  157. }
  158. var inherits = _inherits;
  159. var _typeof_1 = createCommonjsModule(function (module) {
  160. function _typeof(obj) {
  161. "@babel/helpers - typeof";
  162. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  163. module.exports = _typeof = function _typeof(obj) {
  164. return typeof obj;
  165. };
  166. } else {
  167. module.exports = _typeof = function _typeof(obj) {
  168. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  169. };
  170. }
  171. return _typeof(obj);
  172. }
  173. module.exports = _typeof;
  174. });
  175. function _assertThisInitialized(self) {
  176. if (self === void 0) {
  177. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  178. }
  179. return self;
  180. }
  181. var assertThisInitialized = _assertThisInitialized;
  182. function _possibleConstructorReturn(self, call) {
  183. if (call && (_typeof_1(call) === "object" || typeof call === "function")) {
  184. return call;
  185. }
  186. return assertThisInitialized(self);
  187. }
  188. var possibleConstructorReturn = _possibleConstructorReturn;
  189. var runtime_1 = createCommonjsModule(function (module) {
  190. /**
  191. * Copyright (c) 2014-present, Facebook, Inc.
  192. *
  193. * This source code is licensed under the MIT license found in the
  194. * LICENSE file in the root directory of this source tree.
  195. */
  196. var runtime = (function (exports) {
  197. var Op = Object.prototype;
  198. var hasOwn = Op.hasOwnProperty;
  199. var undefined$1; // More compressible than void 0.
  200. var $Symbol = typeof Symbol === "function" ? Symbol : {};
  201. var iteratorSymbol = $Symbol.iterator || "@@iterator";
  202. var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  203. var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  204. function define(obj, key, value) {
  205. Object.defineProperty(obj, key, {
  206. value: value,
  207. enumerable: true,
  208. configurable: true,
  209. writable: true
  210. });
  211. return obj[key];
  212. }
  213. try {
  214. // IE 8 has a broken Object.defineProperty that only works on DOM objects.
  215. define({}, "");
  216. } catch (err) {
  217. define = function(obj, key, value) {
  218. return obj[key] = value;
  219. };
  220. }
  221. function wrap(innerFn, outerFn, self, tryLocsList) {
  222. // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
  223. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
  224. var generator = Object.create(protoGenerator.prototype);
  225. var context = new Context(tryLocsList || []);
  226. // The ._invoke method unifies the implementations of the .next,
  227. // .throw, and .return methods.
  228. generator._invoke = makeInvokeMethod(innerFn, self, context);
  229. return generator;
  230. }
  231. exports.wrap = wrap;
  232. // Try/catch helper to minimize deoptimizations. Returns a completion
  233. // record like context.tryEntries[i].completion. This interface could
  234. // have been (and was previously) designed to take a closure to be
  235. // invoked without arguments, but in all the cases we care about we
  236. // already have an existing method we want to call, so there's no need
  237. // to create a new function object. We can even get away with assuming
  238. // the method takes exactly one argument, since that happens to be true
  239. // in every case, so we don't have to touch the arguments object. The
  240. // only additional allocation required is the completion record, which
  241. // has a stable shape and so hopefully should be cheap to allocate.
  242. function tryCatch(fn, obj, arg) {
  243. try {
  244. return { type: "normal", arg: fn.call(obj, arg) };
  245. } catch (err) {
  246. return { type: "throw", arg: err };
  247. }
  248. }
  249. var GenStateSuspendedStart = "suspendedStart";
  250. var GenStateSuspendedYield = "suspendedYield";
  251. var GenStateExecuting = "executing";
  252. var GenStateCompleted = "completed";
  253. // Returning this object from the innerFn has the same effect as
  254. // breaking out of the dispatch switch statement.
  255. var ContinueSentinel = {};
  256. // Dummy constructor functions that we use as the .constructor and
  257. // .constructor.prototype properties for functions that return Generator
  258. // objects. For full spec compliance, you may wish to configure your
  259. // minifier not to mangle the names of these two functions.
  260. function Generator() {}
  261. function GeneratorFunction() {}
  262. function GeneratorFunctionPrototype() {}
  263. // This is a polyfill for %IteratorPrototype% for environments that
  264. // don't natively support it.
  265. var IteratorPrototype = {};
  266. IteratorPrototype[iteratorSymbol] = function () {
  267. return this;
  268. };
  269. var getProto = Object.getPrototypeOf;
  270. var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  271. if (NativeIteratorPrototype &&
  272. NativeIteratorPrototype !== Op &&
  273. hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
  274. // This environment has a native %IteratorPrototype%; use it instead
  275. // of the polyfill.
  276. IteratorPrototype = NativeIteratorPrototype;
  277. }
  278. var Gp = GeneratorFunctionPrototype.prototype =
  279. Generator.prototype = Object.create(IteratorPrototype);
  280. GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  281. GeneratorFunctionPrototype.constructor = GeneratorFunction;
  282. GeneratorFunction.displayName = define(
  283. GeneratorFunctionPrototype,
  284. toStringTagSymbol,
  285. "GeneratorFunction"
  286. );
  287. // Helper for defining the .next, .throw, and .return methods of the
  288. // Iterator interface in terms of a single ._invoke method.
  289. function defineIteratorMethods(prototype) {
  290. ["next", "throw", "return"].forEach(function(method) {
  291. define(prototype, method, function(arg) {
  292. return this._invoke(method, arg);
  293. });
  294. });
  295. }
  296. exports.isGeneratorFunction = function(genFun) {
  297. var ctor = typeof genFun === "function" && genFun.constructor;
  298. return ctor
  299. ? ctor === GeneratorFunction ||
  300. // For the native GeneratorFunction constructor, the best we can
  301. // do is to check its .name property.
  302. (ctor.displayName || ctor.name) === "GeneratorFunction"
  303. : false;
  304. };
  305. exports.mark = function(genFun) {
  306. if (Object.setPrototypeOf) {
  307. Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
  308. } else {
  309. genFun.__proto__ = GeneratorFunctionPrototype;
  310. define(genFun, toStringTagSymbol, "GeneratorFunction");
  311. }
  312. genFun.prototype = Object.create(Gp);
  313. return genFun;
  314. };
  315. // Within the body of any async function, `await x` is transformed to
  316. // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  317. // `hasOwn.call(value, "__await")` to determine if the yielded value is
  318. // meant to be awaited.
  319. exports.awrap = function(arg) {
  320. return { __await: arg };
  321. };
  322. function AsyncIterator(generator, PromiseImpl) {
  323. function invoke(method, arg, resolve, reject) {
  324. var record = tryCatch(generator[method], generator, arg);
  325. if (record.type === "throw") {
  326. reject(record.arg);
  327. } else {
  328. var result = record.arg;
  329. var value = result.value;
  330. if (value &&
  331. typeof value === "object" &&
  332. hasOwn.call(value, "__await")) {
  333. return PromiseImpl.resolve(value.__await).then(function(value) {
  334. invoke("next", value, resolve, reject);
  335. }, function(err) {
  336. invoke("throw", err, resolve, reject);
  337. });
  338. }
  339. return PromiseImpl.resolve(value).then(function(unwrapped) {
  340. // When a yielded Promise is resolved, its final value becomes
  341. // the .value of the Promise<{value,done}> result for the
  342. // current iteration.
  343. result.value = unwrapped;
  344. resolve(result);
  345. }, function(error) {
  346. // If a rejected Promise was yielded, throw the rejection back
  347. // into the async generator function so it can be handled there.
  348. return invoke("throw", error, resolve, reject);
  349. });
  350. }
  351. }
  352. var previousPromise;
  353. function enqueue(method, arg) {
  354. function callInvokeWithMethodAndArg() {
  355. return new PromiseImpl(function(resolve, reject) {
  356. invoke(method, arg, resolve, reject);
  357. });
  358. }
  359. return previousPromise =
  360. // If enqueue has been called before, then we want to wait until
  361. // all previous Promises have been resolved before calling invoke,
  362. // so that results are always delivered in the correct order. If
  363. // enqueue has not been called before, then it is important to
  364. // call invoke immediately, without waiting on a callback to fire,
  365. // so that the async generator function has the opportunity to do
  366. // any necessary setup in a predictable way. This predictability
  367. // is why the Promise constructor synchronously invokes its
  368. // executor callback, and why async functions synchronously
  369. // execute code before the first await. Since we implement simple
  370. // async functions in terms of async generators, it is especially
  371. // important to get this right, even though it requires care.
  372. previousPromise ? previousPromise.then(
  373. callInvokeWithMethodAndArg,
  374. // Avoid propagating failures to Promises returned by later
  375. // invocations of the iterator.
  376. callInvokeWithMethodAndArg
  377. ) : callInvokeWithMethodAndArg();
  378. }
  379. // Define the unified helper method that is used to implement .next,
  380. // .throw, and .return (see defineIteratorMethods).
  381. this._invoke = enqueue;
  382. }
  383. defineIteratorMethods(AsyncIterator.prototype);
  384. AsyncIterator.prototype[asyncIteratorSymbol] = function () {
  385. return this;
  386. };
  387. exports.AsyncIterator = AsyncIterator;
  388. // Note that simple async functions are implemented on top of
  389. // AsyncIterator objects; they just return a Promise for the value of
  390. // the final result produced by the iterator.
  391. exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  392. if (PromiseImpl === void 0) PromiseImpl = Promise;
  393. var iter = new AsyncIterator(
  394. wrap(innerFn, outerFn, self, tryLocsList),
  395. PromiseImpl
  396. );
  397. return exports.isGeneratorFunction(outerFn)
  398. ? iter // If outerFn is a generator, return the full iterator.
  399. : iter.next().then(function(result) {
  400. return result.done ? result.value : iter.next();
  401. });
  402. };
  403. function makeInvokeMethod(innerFn, self, context) {
  404. var state = GenStateSuspendedStart;
  405. return function invoke(method, arg) {
  406. if (state === GenStateExecuting) {
  407. throw new Error("Generator is already running");
  408. }
  409. if (state === GenStateCompleted) {
  410. if (method === "throw") {
  411. throw arg;
  412. }
  413. // Be forgiving, per 25.3.3.3.3 of the spec:
  414. // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
  415. return doneResult();
  416. }
  417. context.method = method;
  418. context.arg = arg;
  419. while (true) {
  420. var delegate = context.delegate;
  421. if (delegate) {
  422. var delegateResult = maybeInvokeDelegate(delegate, context);
  423. if (delegateResult) {
  424. if (delegateResult === ContinueSentinel) continue;
  425. return delegateResult;
  426. }
  427. }
  428. if (context.method === "next") {
  429. // Setting context._sent for legacy support of Babel's
  430. // function.sent implementation.
  431. context.sent = context._sent = context.arg;
  432. } else if (context.method === "throw") {
  433. if (state === GenStateSuspendedStart) {
  434. state = GenStateCompleted;
  435. throw context.arg;
  436. }
  437. context.dispatchException(context.arg);
  438. } else if (context.method === "return") {
  439. context.abrupt("return", context.arg);
  440. }
  441. state = GenStateExecuting;
  442. var record = tryCatch(innerFn, self, context);
  443. if (record.type === "normal") {
  444. // If an exception is thrown from innerFn, we leave state ===
  445. // GenStateExecuting and loop back for another invocation.
  446. state = context.done
  447. ? GenStateCompleted
  448. : GenStateSuspendedYield;
  449. if (record.arg === ContinueSentinel) {
  450. continue;
  451. }
  452. return {
  453. value: record.arg,
  454. done: context.done
  455. };
  456. } else if (record.type === "throw") {
  457. state = GenStateCompleted;
  458. // Dispatch the exception by looping back around to the
  459. // context.dispatchException(context.arg) call above.
  460. context.method = "throw";
  461. context.arg = record.arg;
  462. }
  463. }
  464. };
  465. }
  466. // Call delegate.iterator[context.method](context.arg) and handle the
  467. // result, either by returning a { value, done } result from the
  468. // delegate iterator, or by modifying context.method and context.arg,
  469. // setting context.delegate to null, and returning the ContinueSentinel.
  470. function maybeInvokeDelegate(delegate, context) {
  471. var method = delegate.iterator[context.method];
  472. if (method === undefined$1) {
  473. // A .throw or .return when the delegate iterator has no .throw
  474. // method always terminates the yield* loop.
  475. context.delegate = null;
  476. if (context.method === "throw") {
  477. // Note: ["return"] must be used for ES3 parsing compatibility.
  478. if (delegate.iterator["return"]) {
  479. // If the delegate iterator has a return method, give it a
  480. // chance to clean up.
  481. context.method = "return";
  482. context.arg = undefined$1;
  483. maybeInvokeDelegate(delegate, context);
  484. if (context.method === "throw") {
  485. // If maybeInvokeDelegate(context) changed context.method from
  486. // "return" to "throw", let that override the TypeError below.
  487. return ContinueSentinel;
  488. }
  489. }
  490. context.method = "throw";
  491. context.arg = new TypeError(
  492. "The iterator does not provide a 'throw' method");
  493. }
  494. return ContinueSentinel;
  495. }
  496. var record = tryCatch(method, delegate.iterator, context.arg);
  497. if (record.type === "throw") {
  498. context.method = "throw";
  499. context.arg = record.arg;
  500. context.delegate = null;
  501. return ContinueSentinel;
  502. }
  503. var info = record.arg;
  504. if (! info) {
  505. context.method = "throw";
  506. context.arg = new TypeError("iterator result is not an object");
  507. context.delegate = null;
  508. return ContinueSentinel;
  509. }
  510. if (info.done) {
  511. // Assign the result of the finished delegate to the temporary
  512. // variable specified by delegate.resultName (see delegateYield).
  513. context[delegate.resultName] = info.value;
  514. // Resume execution at the desired location (see delegateYield).
  515. context.next = delegate.nextLoc;
  516. // If context.method was "throw" but the delegate handled the
  517. // exception, let the outer generator proceed normally. If
  518. // context.method was "next", forget context.arg since it has been
  519. // "consumed" by the delegate iterator. If context.method was
  520. // "return", allow the original .return call to continue in the
  521. // outer generator.
  522. if (context.method !== "return") {
  523. context.method = "next";
  524. context.arg = undefined$1;
  525. }
  526. } else {
  527. // Re-yield the result returned by the delegate method.
  528. return info;
  529. }
  530. // The delegate iterator is finished, so forget it and continue with
  531. // the outer generator.
  532. context.delegate = null;
  533. return ContinueSentinel;
  534. }
  535. // Define Generator.prototype.{next,throw,return} in terms of the
  536. // unified ._invoke helper method.
  537. defineIteratorMethods(Gp);
  538. define(Gp, toStringTagSymbol, "Generator");
  539. // A Generator should always return itself as the iterator object when the
  540. // @@iterator function is called on it. Some browsers' implementations of the
  541. // iterator prototype chain incorrectly implement this, causing the Generator
  542. // object to not be returned from this call. This ensures that doesn't happen.
  543. // See https://github.com/facebook/regenerator/issues/274 for more details.
  544. Gp[iteratorSymbol] = function() {
  545. return this;
  546. };
  547. Gp.toString = function() {
  548. return "[object Generator]";
  549. };
  550. function pushTryEntry(locs) {
  551. var entry = { tryLoc: locs[0] };
  552. if (1 in locs) {
  553. entry.catchLoc = locs[1];
  554. }
  555. if (2 in locs) {
  556. entry.finallyLoc = locs[2];
  557. entry.afterLoc = locs[3];
  558. }
  559. this.tryEntries.push(entry);
  560. }
  561. function resetTryEntry(entry) {
  562. var record = entry.completion || {};
  563. record.type = "normal";
  564. delete record.arg;
  565. entry.completion = record;
  566. }
  567. function Context(tryLocsList) {
  568. // The root entry object (effectively a try statement without a catch
  569. // or a finally block) gives us a place to store values thrown from
  570. // locations where there is no enclosing try statement.
  571. this.tryEntries = [{ tryLoc: "root" }];
  572. tryLocsList.forEach(pushTryEntry, this);
  573. this.reset(true);
  574. }
  575. exports.keys = function(object) {
  576. var keys = [];
  577. for (var key in object) {
  578. keys.push(key);
  579. }
  580. keys.reverse();
  581. // Rather than returning an object with a next method, we keep
  582. // things simple and return the next function itself.
  583. return function next() {
  584. while (keys.length) {
  585. var key = keys.pop();
  586. if (key in object) {
  587. next.value = key;
  588. next.done = false;
  589. return next;
  590. }
  591. }
  592. // To avoid creating an additional object, we just hang the .value
  593. // and .done properties off the next function object itself. This
  594. // also ensures that the minifier will not anonymize the function.
  595. next.done = true;
  596. return next;
  597. };
  598. };
  599. function values(iterable) {
  600. if (iterable) {
  601. var iteratorMethod = iterable[iteratorSymbol];
  602. if (iteratorMethod) {
  603. return iteratorMethod.call(iterable);
  604. }
  605. if (typeof iterable.next === "function") {
  606. return iterable;
  607. }
  608. if (!isNaN(iterable.length)) {
  609. var i = -1, next = function next() {
  610. while (++i < iterable.length) {
  611. if (hasOwn.call(iterable, i)) {
  612. next.value = iterable[i];
  613. next.done = false;
  614. return next;
  615. }
  616. }
  617. next.value = undefined$1;
  618. next.done = true;
  619. return next;
  620. };
  621. return next.next = next;
  622. }
  623. }
  624. // Return an iterator with no values.
  625. return { next: doneResult };
  626. }
  627. exports.values = values;
  628. function doneResult() {
  629. return { value: undefined$1, done: true };
  630. }
  631. Context.prototype = {
  632. constructor: Context,
  633. reset: function(skipTempReset) {
  634. this.prev = 0;
  635. this.next = 0;
  636. // Resetting context._sent for legacy support of Babel's
  637. // function.sent implementation.
  638. this.sent = this._sent = undefined$1;
  639. this.done = false;
  640. this.delegate = null;
  641. this.method = "next";
  642. this.arg = undefined$1;
  643. this.tryEntries.forEach(resetTryEntry);
  644. if (!skipTempReset) {
  645. for (var name in this) {
  646. // Not sure about the optimal order of these conditions:
  647. if (name.charAt(0) === "t" &&
  648. hasOwn.call(this, name) &&
  649. !isNaN(+name.slice(1))) {
  650. this[name] = undefined$1;
  651. }
  652. }
  653. }
  654. },
  655. stop: function() {
  656. this.done = true;
  657. var rootEntry = this.tryEntries[0];
  658. var rootRecord = rootEntry.completion;
  659. if (rootRecord.type === "throw") {
  660. throw rootRecord.arg;
  661. }
  662. return this.rval;
  663. },
  664. dispatchException: function(exception) {
  665. if (this.done) {
  666. throw exception;
  667. }
  668. var context = this;
  669. function handle(loc, caught) {
  670. record.type = "throw";
  671. record.arg = exception;
  672. context.next = loc;
  673. if (caught) {
  674. // If the dispatched exception was caught by a catch block,
  675. // then let that catch block handle the exception normally.
  676. context.method = "next";
  677. context.arg = undefined$1;
  678. }
  679. return !! caught;
  680. }
  681. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  682. var entry = this.tryEntries[i];
  683. var record = entry.completion;
  684. if (entry.tryLoc === "root") {
  685. // Exception thrown outside of any try block that could handle
  686. // it, so set the completion value of the entire function to
  687. // throw the exception.
  688. return handle("end");
  689. }
  690. if (entry.tryLoc <= this.prev) {
  691. var hasCatch = hasOwn.call(entry, "catchLoc");
  692. var hasFinally = hasOwn.call(entry, "finallyLoc");
  693. if (hasCatch && hasFinally) {
  694. if (this.prev < entry.catchLoc) {
  695. return handle(entry.catchLoc, true);
  696. } else if (this.prev < entry.finallyLoc) {
  697. return handle(entry.finallyLoc);
  698. }
  699. } else if (hasCatch) {
  700. if (this.prev < entry.catchLoc) {
  701. return handle(entry.catchLoc, true);
  702. }
  703. } else if (hasFinally) {
  704. if (this.prev < entry.finallyLoc) {
  705. return handle(entry.finallyLoc);
  706. }
  707. } else {
  708. throw new Error("try statement without catch or finally");
  709. }
  710. }
  711. }
  712. },
  713. abrupt: function(type, arg) {
  714. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  715. var entry = this.tryEntries[i];
  716. if (entry.tryLoc <= this.prev &&
  717. hasOwn.call(entry, "finallyLoc") &&
  718. this.prev < entry.finallyLoc) {
  719. var finallyEntry = entry;
  720. break;
  721. }
  722. }
  723. if (finallyEntry &&
  724. (type === "break" ||
  725. type === "continue") &&
  726. finallyEntry.tryLoc <= arg &&
  727. arg <= finallyEntry.finallyLoc) {
  728. // Ignore the finally entry if control is not jumping to a
  729. // location outside the try/catch block.
  730. finallyEntry = null;
  731. }
  732. var record = finallyEntry ? finallyEntry.completion : {};
  733. record.type = type;
  734. record.arg = arg;
  735. if (finallyEntry) {
  736. this.method = "next";
  737. this.next = finallyEntry.finallyLoc;
  738. return ContinueSentinel;
  739. }
  740. return this.complete(record);
  741. },
  742. complete: function(record, afterLoc) {
  743. if (record.type === "throw") {
  744. throw record.arg;
  745. }
  746. if (record.type === "break" ||
  747. record.type === "continue") {
  748. this.next = record.arg;
  749. } else if (record.type === "return") {
  750. this.rval = this.arg = record.arg;
  751. this.method = "return";
  752. this.next = "end";
  753. } else if (record.type === "normal" && afterLoc) {
  754. this.next = afterLoc;
  755. }
  756. return ContinueSentinel;
  757. },
  758. finish: function(finallyLoc) {
  759. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  760. var entry = this.tryEntries[i];
  761. if (entry.finallyLoc === finallyLoc) {
  762. this.complete(entry.completion, entry.afterLoc);
  763. resetTryEntry(entry);
  764. return ContinueSentinel;
  765. }
  766. }
  767. },
  768. "catch": function(tryLoc) {
  769. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  770. var entry = this.tryEntries[i];
  771. if (entry.tryLoc === tryLoc) {
  772. var record = entry.completion;
  773. if (record.type === "throw") {
  774. var thrown = record.arg;
  775. resetTryEntry(entry);
  776. }
  777. return thrown;
  778. }
  779. }
  780. // The context.catch method must only be called with a location
  781. // argument that corresponds to a known catch block.
  782. throw new Error("illegal catch attempt");
  783. },
  784. delegateYield: function(iterable, resultName, nextLoc) {
  785. this.delegate = {
  786. iterator: values(iterable),
  787. resultName: resultName,
  788. nextLoc: nextLoc
  789. };
  790. if (this.method === "next") {
  791. // Deliberately forget the last sent value so that we don't
  792. // accidentally pass it on to the delegate.
  793. this.arg = undefined$1;
  794. }
  795. return ContinueSentinel;
  796. }
  797. };
  798. // Regardless of whether this script is executing as a CommonJS module
  799. // or not, return the runtime object so that we can declare the variable
  800. // regeneratorRuntime in the outer scope, which allows this module to be
  801. // injected easily by `bin/regenerator --include-runtime script.js`.
  802. return exports;
  803. }(
  804. // If this script is executing as a CommonJS module, use module.exports
  805. // as the regeneratorRuntime namespace. Otherwise create a new empty
  806. // object. Either way, the resulting object will be used to initialize
  807. // the regeneratorRuntime variable at the top of this file.
  808. module.exports
  809. ));
  810. try {
  811. regeneratorRuntime = runtime;
  812. } catch (accidentalStrictMode) {
  813. // This module should not be running in strict mode, so the above
  814. // assignment should always work unless something is misconfigured. Just
  815. // in case runtime.js accidentally runs in strict mode, we can escape
  816. // strict mode using a global Function call. This could conceivably fail
  817. // if a Content Security Policy forbids using Function, but in that case
  818. // the proper solution is to fix the accidental strict mode problem. If
  819. // you've misconfigured your bundler to force strict mode and applied a
  820. // CSP to forbid Function, and you're not willing to fix either of those
  821. // problems, please detail your unique predicament in a GitHub issue.
  822. Function("r", "regeneratorRuntime = r")(runtime);
  823. }
  824. });
  825. var regenerator = runtime_1;
  826. /*! *****************************************************************************
  827. Copyright (c) Microsoft Corporation.
  828. Permission to use, copy, modify, and/or distribute this software for any
  829. purpose with or without fee is hereby granted.
  830. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  831. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  832. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  833. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  834. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  835. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  836. PERFORMANCE OF THIS SOFTWARE.
  837. ***************************************************************************** */
  838. function __awaiter(thisArg, _arguments, P, generator) {
  839. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  840. return new (P || (P = Promise))(function (resolve, reject) {
  841. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  842. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  843. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  844. step((generator = generator.apply(thisArg, _arguments || [])).next());
  845. });
  846. }
  847. /*
  848. * Tencent is pleased to support the open source community by making vap available.
  849. *
  850. * Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
  851. *
  852. * Licensed under the MIT License (the "License"); you may not use this file except in
  853. * compliance with the License. You may obtain a copy of the License at
  854. *
  855. * http://opensource.org/licenses/MIT
  856. *
  857. * Unless required by applicable law or agreed to in writing, software distributed under the License is
  858. * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  859. * either express or implied. See the License for the specific language governing permissions and
  860. * limitations under the License.
  861. */
  862. var FrameParser = /*#__PURE__*/function () {
  863. function FrameParser(source, headData) {
  864. classCallCheck(this, FrameParser);
  865. this.config = source || {};
  866. this.headData = headData;
  867. this.frame = [];
  868. this.textureMap = {};
  869. }
  870. createClass(FrameParser, [{
  871. key: "init",
  872. value: function init() {
  873. return __awaiter(this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee() {
  874. return regenerator.wrap(function _callee$(_context) {
  875. while (1) {
  876. switch (_context.prev = _context.next) {
  877. case 0:
  878. if (!/\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]\.json/.test(this.config)) {
  879. _context.next = 4;
  880. break;
  881. }
  882. _context.next = 3;
  883. return this.getConfigBySrc(this.config);
  884. case 3:
  885. this.config = _context.sent;
  886. case 4:
  887. _context.next = 6;
  888. return this.parseSrc(this.config);
  889. case 6:
  890. this.frame = this.config.frame || [];
  891. return _context.abrupt("return", this);
  892. case 8:
  893. case "end":
  894. return _context.stop();
  895. }
  896. }
  897. }, _callee, this);
  898. }));
  899. }
  900. }, {
  901. key: "initCanvas",
  902. value: function initCanvas() {
  903. if (!this.canvas) {
  904. var canvas = document.createElement('canvas');
  905. var ctx = canvas.getContext('2d');
  906. canvas.style.display = 'none';
  907. document.body.appendChild(canvas);
  908. this.ctx = ctx;
  909. this.canvas = canvas;
  910. }
  911. }
  912. }, {
  913. key: "loadImg",
  914. value: function loadImg(url) {
  915. return new Promise(function (resolve, reject) {
  916. // console.log('load img:', url)
  917. var img = new Image();
  918. img.crossOrigin = 'anonymous';
  919. img.onload = function () {
  920. resolve(this);
  921. };
  922. img.onerror = function (e) {
  923. console.error('frame 资源加载失败:' + url);
  924. reject(new Error('frame 资源加载失败:' + url));
  925. };
  926. img.src = url;
  927. });
  928. }
  929. }, {
  930. key: "parseSrc",
  931. value: function parseSrc(dataJson) {
  932. var _this = this;
  933. var src = this.srcData = {};
  934. return Promise.all((dataJson.src || []).map(function (item) {
  935. return __awaiter(_this, void 0, void 0, /*#__PURE__*/regenerator.mark(function _callee2() {
  936. var _this2 = this;
  937. return regenerator.wrap(function _callee2$(_context2) {
  938. while (1) {
  939. switch (_context2.prev = _context2.next) {
  940. case 0:
  941. item.img = null;
  942. if (!(!this.headData[item.srcTag.slice(1, item.srcTag.length - 1)] && !this.headData[item.srcTag])) {
  943. _context2.next = 5;
  944. break;
  945. }
  946. console.warn("vap: \u878D\u5408\u4FE1\u606F\u6CA1\u6709\u4F20\u5165\uFF1A".concat(item.srcTag));
  947. _context2.next = 23;
  948. break;
  949. case 5:
  950. if (!(item.srcType === 'txt')) {
  951. _context2.next = 12;
  952. break;
  953. }
  954. if (this.headData['fontStyle'] && !item['fontStyle']) {
  955. item['fontStyle'] = this.headData['fontStyle'];
  956. }
  957. item.textStr = this.headData[item.srcTag] || item.srcTag.replace(/\[(.*)\]/, function ($0, $1) {
  958. return _this2.headData[$1];
  959. });
  960. this.initCanvas();
  961. item.img = this.makeTextImg(item);
  962. _context2.next = 22;
  963. break;
  964. case 12:
  965. if (!(item.srcType === 'img')) {
  966. _context2.next = 22;
  967. break;
  968. }
  969. item.imgUrl = this.headData[item.srcTag] || item.srcTag.replace(/\[(.*)\]/, function ($0, $1) {
  970. return _this2.headData[$1];
  971. });
  972. _context2.prev = 14;
  973. _context2.next = 17;
  974. return this.loadImg(item.imgUrl);
  975. case 17:
  976. item.img = _context2.sent;
  977. _context2.next = 22;
  978. break;
  979. case 20:
  980. _context2.prev = 20;
  981. _context2.t0 = _context2["catch"](14);
  982. case 22:
  983. if (item.img) {
  984. src[item.srcId] = item;
  985. }
  986. case 23:
  987. case "end":
  988. return _context2.stop();
  989. }
  990. }
  991. }, _callee2, this, [[14, 20]]);
  992. }));
  993. })).then(function () {
  994. if (_this.canvas) {
  995. _this.canvas.parentNode.removeChild(_this.canvas);
  996. }
  997. });
  998. }
  999. /**
  1000. * 下载json文件
  1001. * @param jsonUrl json外链
  1002. * @returns {Promise}
  1003. */
  1004. }, {
  1005. key: "getConfigBySrc",
  1006. value: function getConfigBySrc(jsonUrl) {
  1007. return new Promise(function (resolve, reject) {
  1008. var xhr = new XMLHttpRequest();
  1009. xhr.open('GET', jsonUrl, true);
  1010. xhr.responseType = 'json';
  1011. xhr.onload = function () {
  1012. if (xhr.status === 200 || xhr.status === 304 && xhr.response) {
  1013. var res = xhr.response;
  1014. resolve(res);
  1015. } else {
  1016. reject(new Error('http response invalid' + xhr.status));
  1017. }
  1018. };
  1019. xhr.send();
  1020. });
  1021. }
  1022. /**
  1023. * 文字转换图片
  1024. * @param item
  1025. */
  1026. }, {
  1027. key: "makeTextImg",
  1028. value: function makeTextImg(item) {
  1029. var textStr = item.textStr,
  1030. w = item.w,
  1031. h = item.h,
  1032. color = item.color,
  1033. style = item.style,
  1034. fontStyle = item.fontStyle;
  1035. var ctx = this.ctx;
  1036. ctx.canvas.width = w;
  1037. ctx.canvas.height = h;
  1038. ctx.textBaseline = 'middle';
  1039. ctx.textAlign = 'center';
  1040. var getFontStyle = function getFontStyle() {
  1041. var fontSize = Math.min(w / textStr.length, h - 8); // 需留一定间隙
  1042. var font = ["".concat(fontSize, "px"), 'Arial'];
  1043. if (style === 'b') {
  1044. font.unshift('bold');
  1045. }
  1046. return font.join(' ');
  1047. };
  1048. if (!fontStyle) {
  1049. ctx.font = getFontStyle();
  1050. ctx.fillStyle = color;
  1051. } else if (typeof fontStyle == 'string') {
  1052. ctx.font = fontStyle;
  1053. ctx.fillStyle = color;
  1054. } else if (_typeof_1(fontStyle) == 'object') {
  1055. ctx.font = fontStyle['font'] || getFontStyle();
  1056. ctx.fillStyle = fontStyle['color'] || color;
  1057. } else if (typeof fontStyle == 'function') {
  1058. ctx.font = getFontStyle();
  1059. ctx.fillStyle = color;
  1060. fontStyle.call(null, ctx, item);
  1061. }
  1062. ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  1063. ctx.fillText(textStr, w / 2, h / 2); // console.log('frame : ' + textStr, ctx.canvas.toDataURL('image/png'))
  1064. return ctx.getImageData(0, 0, w, h);
  1065. }
  1066. }, {
  1067. key: "getFrame",
  1068. value: function getFrame(frame) {
  1069. return this.frame.find(function (item) {
  1070. return item.i === frame;
  1071. });
  1072. }
  1073. }]);
  1074. return FrameParser;
  1075. }();
  1076. /*
  1077. * Tencent is pleased to support the open source community by making vap available.
  1078. *
  1079. * Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
  1080. *
  1081. * Licensed under the MIT License (the "License"); you may not use this file except in
  1082. * compliance with the License. You may obtain a copy of the License at
  1083. *
  1084. * http://opensource.org/licenses/MIT
  1085. *
  1086. * Unless required by applicable law or agreed to in writing, software distributed under the License is
  1087. * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  1088. * either express or implied. See the License for the specific language governing permissions and
  1089. * limitations under the License.
  1090. */
  1091. function createShader(gl, type, source) {
  1092. var shader = gl.createShader(type);
  1093. gl.shaderSource(shader, source);
  1094. gl.compileShader(shader); // if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  1095. // console.error(gl.getShaderInfoLog(shader))
  1096. // }
  1097. return shader;
  1098. }
  1099. function createProgram(gl, vertexShader, fragmentShader) {
  1100. var program = gl.createProgram();
  1101. gl.attachShader(program, vertexShader);
  1102. gl.attachShader(program, fragmentShader);
  1103. gl.linkProgram(program); // if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  1104. // console.error(gl.getProgramInfoLog(program))
  1105. // }
  1106. gl.useProgram(program);
  1107. return program;
  1108. }
  1109. function createTexture(gl, index, imgData) {
  1110. var texture = gl.createTexture();
  1111. var textrueIndex = gl.TEXTURE0 + index;
  1112. gl.activeTexture(textrueIndex);
  1113. gl.bindTexture(gl.TEXTURE_2D, texture); // gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  1114. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  1115. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  1116. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1117. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1118. if (imgData) {
  1119. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, imgData);
  1120. }
  1121. return texture;
  1122. }
  1123. function cleanWebGL(gl, _ref) {
  1124. var _ref$shaders = _ref.shaders,
  1125. shaders = _ref$shaders === void 0 ? [] : _ref$shaders,
  1126. _ref$program = _ref.program,
  1127. program = _ref$program === void 0 ? null : _ref$program,
  1128. _ref$textures = _ref.textures,
  1129. textures = _ref$textures === void 0 ? [] : _ref$textures,
  1130. _ref$buffers = _ref.buffers,
  1131. buffers = _ref$buffers === void 0 ? [] : _ref$buffers;
  1132. try {
  1133. textures.forEach(function (t) {
  1134. gl.deleteTexture(t);
  1135. });
  1136. buffers.forEach(function (b) {
  1137. gl.deleteBuffer(b);
  1138. });
  1139. if (program) {
  1140. shaders.forEach(function (shader) {
  1141. gl.detachShader(program, shader);
  1142. gl.deleteShader(shader);
  1143. });
  1144. gl.deleteProgram(program);
  1145. }
  1146. } catch (e) {}
  1147. }
  1148. var VapVideo = /*#__PURE__*/function () {
  1149. function VapVideo() {
  1150. classCallCheck(this, VapVideo);
  1151. this.events = {};
  1152. this.firstPlaying = true;
  1153. this.customEvent = ['frame', 'percentage', ''];
  1154. }
  1155. createClass(VapVideo, [{
  1156. key: "setOptions",
  1157. value: function setOptions(options) {
  1158. if (!options.container || !options.src) {
  1159. console.warn('[Alpha video]: options container and src cannot be empty!');
  1160. }
  1161. this.options = Object.assign({
  1162. // 视频url
  1163. src: '',
  1164. // 循环播放
  1165. loop: false,
  1166. fps: 20,
  1167. // 容器
  1168. container: null,
  1169. // 是否预加载视频资源
  1170. precache: false,
  1171. // 是否静音播放
  1172. mute: false,
  1173. config: '',
  1174. accurate: false,
  1175. // 帧偏移, 一般没用, 预留支持问题素材
  1176. offset: 0
  1177. }, options);
  1178. this.setBegin = true;
  1179. this.useFrameCallback = false;
  1180. this.container = this.options.container;
  1181. if (!this.options.src || !this.options.config || !this.options.container) {
  1182. console.error('参数出错:src(视频地址)、config(配置文件地址)、container(dom容器)');
  1183. }
  1184. return this;
  1185. }
  1186. }, {
  1187. key: "precacheSource",
  1188. value: function precacheSource(source) {
  1189. var URL = window.webkitURL || window.URL;
  1190. return new Promise(function (resolve, reject) {
  1191. var xhr = new XMLHttpRequest();
  1192. xhr.open('GET', source, true);
  1193. xhr.responseType = 'blob';
  1194. xhr.onload = function () {
  1195. if (xhr.status === 200 || xhr.status === 304) {
  1196. var res = xhr.response;
  1197. if (/iphone|ipad|ipod/i.test(navigator.userAgent)) {
  1198. var fileReader = new FileReader();
  1199. fileReader.onloadend = function () {
  1200. var resultStr = fileReader.result;
  1201. var raw = atob(resultStr.slice(resultStr.indexOf(',') + 1));
  1202. var buf = Array(raw.length);
  1203. for (var d = 0; d < raw.length; d++) {
  1204. buf[d] = raw.charCodeAt(d);
  1205. }
  1206. var arr = new Uint8Array(buf);
  1207. var blob = new Blob([arr], {
  1208. type: 'video/mp4'
  1209. });
  1210. resolve(URL.createObjectURL(blob));
  1211. };
  1212. fileReader.readAsDataURL(xhr.response);
  1213. } else {
  1214. resolve(URL.createObjectURL(res));
  1215. }
  1216. } else {
  1217. reject(new Error('http response invalid' + xhr.status));
  1218. }
  1219. };
  1220. xhr.send();
  1221. });
  1222. }
  1223. }, {
  1224. key: "initVideo",
  1225. value: function initVideo() {
  1226. var _this = this;
  1227. var options = this.options; // 创建video
  1228. var video = this.video;
  1229. if (!video) {
  1230. video = this.video = document.createElement('video');
  1231. }
  1232. video.crossOrigin = 'anonymous';
  1233. video.autoplay = false;
  1234. video.preload = 'auto';
  1235. video.setAttribute('playsinline', '');
  1236. video.setAttribute('webkit-playsinline', '');
  1237. if (options.mute) {
  1238. video.muted = true;
  1239. video.volume = 0;
  1240. }
  1241. video.style.display = 'none';
  1242. video.loop = !!options.loop;
  1243. if (options.precache) {
  1244. this.precacheSource(options.src).then(function (blob) {
  1245. console.log('sample precached.');
  1246. video.src = blob;
  1247. document.body.appendChild(video);
  1248. })["catch"](function (e) {
  1249. console.error(e);
  1250. });
  1251. } else {
  1252. video.src = options.src; // 这里要插在body上,避免container移动带来无法播放的问题
  1253. document.body.appendChild(this.video);
  1254. video.load();
  1255. }
  1256. this.firstPlaying = true;
  1257. if ('requestVideoFrameCallback' in this.video) {
  1258. this.useFrameCallback = !!this.options.accurate;
  1259. }
  1260. this.cancelRequestAnimation(); // 绑定事件
  1261. this.offAll();
  1262. ['playing', 'error', 'canplay'].forEach(function (item) {
  1263. _this.on(item, _this['on' + item].bind(_this));
  1264. });
  1265. }
  1266. }, {
  1267. key: "drawFrame",
  1268. value: function drawFrame(_, _info) {
  1269. this._drawFrame = this._drawFrame || this.drawFrame.bind(this);
  1270. if (this.useFrameCallback) {
  1271. // @ts-ignore
  1272. this.animId = this.video.requestVideoFrameCallback(this._drawFrame);
  1273. } else {
  1274. this.animId = this.requestAnim(this._drawFrame);
  1275. }
  1276. }
  1277. }, {
  1278. key: "play",
  1279. value: function play() {
  1280. var _this2 = this;
  1281. if (this.useFrameCallback) {
  1282. // @ts-ignore
  1283. this.animId = this.video.requestVideoFrameCallback(this.drawFrame.bind(this));
  1284. } else {
  1285. this.requestAnim = this.requestAnimFunc();
  1286. }
  1287. var prom = this.video && this.video.play();
  1288. if (prom && prom.then) {
  1289. prom["catch"](function (e) {
  1290. if (!_this2.video) {
  1291. return;
  1292. }
  1293. _this2.video.muted = true;
  1294. _this2.video.volume = 0;
  1295. _this2.video.play()["catch"](function (e) {
  1296. _this2.trigger('error', e);
  1297. });
  1298. });
  1299. }
  1300. }
  1301. }, {
  1302. key: "pause",
  1303. value: function pause() {
  1304. this.video && this.video.pause();
  1305. }
  1306. }, {
  1307. key: "setTime",
  1308. value: function setTime(t) {
  1309. if (this.video) {
  1310. this.video.currentTime = t;
  1311. }
  1312. }
  1313. }, {
  1314. key: "requestAnimFunc",
  1315. value: function requestAnimFunc() {
  1316. var _this3 = this;
  1317. var _this$options$fps = this.options.fps,
  1318. fps = _this$options$fps === void 0 ? 30 : _this$options$fps;
  1319. if (window.requestAnimationFrame) {
  1320. var index = -1;
  1321. return function (cb) {
  1322. index++;
  1323. return requestAnimationFrame(function () {
  1324. if (!(index % (60 / fps))) {
  1325. return cb();
  1326. }
  1327. _this3.animId = _this3.requestAnim(cb);
  1328. });
  1329. };
  1330. }
  1331. return function (cb) {
  1332. return window.setTimeout(cb, 1000 / fps);
  1333. };
  1334. }
  1335. }, {
  1336. key: "cancelRequestAnimation",
  1337. value: function cancelRequestAnimation() {
  1338. if (!this.animId) {
  1339. return;
  1340. }
  1341. if (this.useFrameCallback) {
  1342. try {
  1343. // @ts-ignore
  1344. this.video.cancelVideoFrameCallback(this.animId);
  1345. } catch (e) {
  1346. console.error(e);
  1347. }
  1348. } else if (window.cancelAnimationFrame) {
  1349. cancelAnimationFrame(this.animId);
  1350. } else {
  1351. clearTimeout(this.animId);
  1352. }
  1353. this.animId = 0;
  1354. }
  1355. }, {
  1356. key: "clear",
  1357. value: function clear() {
  1358. this.cancelRequestAnimation();
  1359. }
  1360. }, {
  1361. key: "destroy",
  1362. value: function destroy() {
  1363. this.cancelRequestAnimation();
  1364. if (this.video) {
  1365. this.offAll();
  1366. this.video.parentNode && this.video.parentNode.removeChild(this.video);
  1367. this.video = null;
  1368. }
  1369. this.options.onDestroy && this.options.onDestroy();
  1370. }
  1371. }, {
  1372. key: "on",
  1373. value: function on(event, callback) {
  1374. var cbs = this.events[event] || [];
  1375. cbs.push(callback);
  1376. this.events[event] = cbs;
  1377. if (this.customEvent.indexOf(event) === -1) {
  1378. this.video.addEventListener(event, callback);
  1379. }
  1380. return this;
  1381. }
  1382. }, {
  1383. key: "once",
  1384. value: function once(event, callback) {
  1385. var _this4 = this;
  1386. var once = function once() {
  1387. var cbs = _this4.events[event];
  1388. cbs.splice(cbs.indexOf(once), 1);
  1389. _this4.video.removeEventListener(event, once);
  1390. callback.apply(void 0, arguments);
  1391. };
  1392. return this.on(event, once);
  1393. }
  1394. }, {
  1395. key: "trigger",
  1396. value: function trigger(eventName) {
  1397. for (var _len = arguments.length, e = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  1398. e[_key - 1] = arguments[_key];
  1399. }
  1400. try {
  1401. (this.events[eventName] || []).forEach(function (item) {
  1402. item.apply(void 0, e);
  1403. });
  1404. } catch (e) {
  1405. console.error(e);
  1406. }
  1407. }
  1408. }, {
  1409. key: "offAll",
  1410. value: function offAll() {
  1411. var _this5 = this;
  1412. Object.keys(this.events).forEach(function (name) {
  1413. var cbs = _this5.events[name];
  1414. if (cbs && cbs.length) {
  1415. cbs.forEach(function (cb) {
  1416. _this5.video.removeEventListener(name, cb);
  1417. });
  1418. }
  1419. });
  1420. this.events = {};
  1421. return this;
  1422. }
  1423. }, {
  1424. key: "onplaying",
  1425. value: function onplaying() {
  1426. if (this.firstPlaying) {
  1427. this.firstPlaying = false;
  1428. if (!this.useFrameCallback) {
  1429. this.drawFrame(null, null);
  1430. }
  1431. }
  1432. }
  1433. }, {
  1434. key: "oncanplay",
  1435. value: function oncanplay() {
  1436. var begin = this.options.beginPoint;
  1437. if (begin && this.setBegin) {
  1438. this.setBegin = false;
  1439. this.video.currentTime = begin;
  1440. }
  1441. }
  1442. }, {
  1443. key: "onerror",
  1444. value: function onerror(err) {
  1445. console.error('[Alpha video]: play error: ', err);
  1446. this.destroy();
  1447. this.options.onLoadError && this.options.onLoadError(err);
  1448. }
  1449. }]);
  1450. return VapVideo;
  1451. }();
  1452. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
  1453. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
  1454. var PER_SIZE = 9;
  1455. function computeCoord(x, y, w, h, vw, vh) {
  1456. // leftX rightX bottomY topY
  1457. return [x / vw, (x + w) / vw, (vh - y - h) / vh, (vh - y) / vh];
  1458. }
  1459. var WebglRenderVap = /*#__PURE__*/function (_VapVideo) {
  1460. inherits(WebglRenderVap, _VapVideo);
  1461. var _super = _createSuper(WebglRenderVap);
  1462. function WebglRenderVap(options) {
  1463. var _this;
  1464. classCallCheck(this, WebglRenderVap);
  1465. _this = _super.call(this);
  1466. _this.textures = [];
  1467. if (options) {
  1468. _this.play(options);
  1469. }
  1470. return _this;
  1471. }
  1472. createClass(WebglRenderVap, [{
  1473. key: "play",
  1474. value: function play(options) {
  1475. var _this2 = this;
  1476. var _a;
  1477. if (options) {
  1478. this.setOptions(options);
  1479. }
  1480. if (!((_a = this.options) === null || _a === void 0 ? void 0 : _a.config)) {
  1481. console.error("options.config cannot be empty.");
  1482. return this;
  1483. }
  1484. if (options) {
  1485. this.initVideo(); // 重新解析
  1486. this.vapFrameParser = new FrameParser(this.options.config, this.options);
  1487. this.vapFrameParser.init().then(function () {
  1488. _this2.initWebGL();
  1489. _this2.initTexture();
  1490. _this2.initVideoTexture();
  1491. _this2.options.fps = _this2.vapFrameParser.config.info.fps || 30;
  1492. get(getPrototypeOf(WebglRenderVap.prototype), "play", _this2).call(_this2);
  1493. })["catch"](function (e) {
  1494. _this2.vapFrameParser = null;
  1495. console.error('[Alpha video] parse vap frame error.', e);
  1496. return _this2;
  1497. });
  1498. } else {
  1499. get(getPrototypeOf(WebglRenderVap.prototype), "play", this).call(this);
  1500. }
  1501. return this;
  1502. }
  1503. }, {
  1504. key: "initWebGL",
  1505. value: function initWebGL() {
  1506. var canvas = this.canvas,
  1507. gl = this.gl,
  1508. vertexShader = this.vertexShader,
  1509. fragmentShader = this.fragmentShader,
  1510. program = this.program;
  1511. if (!canvas) {
  1512. canvas = document.createElement('canvas');
  1513. }
  1514. var vapFrameParser = this.vapFrameParser;
  1515. var _vapFrameParser$confi = vapFrameParser.config.info,
  1516. w = _vapFrameParser$confi.w,
  1517. h = _vapFrameParser$confi.h;
  1518. canvas.width = w;
  1519. canvas.height = h;
  1520. this.container.appendChild(canvas);
  1521. if (!gl) {
  1522. gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
  1523. gl.disable(gl.BLEND);
  1524. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  1525. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  1526. }
  1527. gl.viewport(0, 0, w, h);
  1528. if (!vertexShader) {
  1529. vertexShader = this.initVertexShader(gl);
  1530. }
  1531. if (fragmentShader && program) {
  1532. cleanWebGL(gl, {
  1533. program: program,
  1534. shaders: [fragmentShader]
  1535. });
  1536. }
  1537. var srcData = vapFrameParser.srcData;
  1538. fragmentShader = this.initFragmentShader(gl, Object.keys(srcData).length);
  1539. program = createProgram(gl, vertexShader, fragmentShader);
  1540. this.canvas = canvas;
  1541. this.gl = gl;
  1542. this.vertexShader = vertexShader;
  1543. this.fragmentShader = fragmentShader;
  1544. this.program = program;
  1545. this.imagePosLoc = null;
  1546. return gl;
  1547. }
  1548. /**
  1549. * 顶点着色器
  1550. */
  1551. }, {
  1552. key: "initVertexShader",
  1553. value: function initVertexShader(gl) {
  1554. return createShader(gl, gl.VERTEX_SHADER, "attribute vec2 a_position; // \u63A5\u53D7\u9876\u70B9\u5750\u6807\n attribute vec2 a_texCoord; // \u63A5\u53D7\u7EB9\u7406\u5750\u6807\n attribute vec2 a_alpha_texCoord; // \u63A5\u53D7\u7EB9\u7406\u5750\u6807\n varying vec2 v_alpha_texCoord; // \u63A5\u53D7\u7EB9\u7406\u5750\u6807\n varying vec2 v_texcoord; // \u4F20\u9012\u7EB9\u7406\u5750\u6807\u7ED9\u7247\u5143\u7740\u8272\u5668\n void main(void){\n gl_Position = vec4(a_position, 0.0, 1.0); // \u8BBE\u7F6E\u5750\u6807\n v_texcoord = a_texCoord; // \u8BBE\u7F6E\u7EB9\u7406\u5750\u6807\n v_alpha_texCoord = a_alpha_texCoord; // \u8BBE\u7F6E\u7EB9\u7406\u5750\u6807\n }");
  1555. }
  1556. /**
  1557. * 片元着色器
  1558. */
  1559. }, {
  1560. key: "initFragmentShader",
  1561. value: function initFragmentShader(gl, textureSize) {
  1562. var bgColor = "vec4(texture2D(u_image_video, v_texcoord).rgb, texture2D(u_image_video,v_alpha_texCoord).r);";
  1563. var sourceTexure = '';
  1564. var sourceUniform = '';
  1565. if (textureSize > 0) {
  1566. var bufferSize = textureSize * PER_SIZE;
  1567. var imgColor = [];
  1568. var samplers = [];
  1569. for (var i = 0; i < textureSize; i++) {
  1570. imgColor.push("if(ndx == ".concat(i + 1, "){\n color = texture2D(u_image").concat(i + 1, ",uv);\n }"));
  1571. samplers.push("uniform sampler2D u_image".concat(i + 1, ";"));
  1572. }
  1573. sourceUniform = "\n ".concat(samplers.join('\n'), "\n uniform float image_pos[").concat(bufferSize, "];\n vec4 getSampleFromArray(int ndx, vec2 uv) {\n vec4 color;\n ").concat(imgColor.join(' else '), "\n return color;\n }\n ");
  1574. sourceTexure = "\n vec4 srcColor,maskColor;\n vec2 srcTexcoord,maskTexcoord;\n int srcIndex;\n float x1,x2,y1,y2,mx1,mx2,my1,my2; //\u663E\u793A\u7684\u533A\u57DF\n\n for(int i=0;i<".concat(bufferSize, ";i+= ").concat(PER_SIZE, "){\n if ((int(image_pos[i]) > 0)) {\n srcIndex = int(image_pos[i]);\n \n x1 = image_pos[i+1];\n x2 = image_pos[i+2];\n y1 = image_pos[i+3];\n y2 = image_pos[i+4];\n \n mx1 = image_pos[i+5];\n mx2 = image_pos[i+6];\n my1 = image_pos[i+7];\n my2 = image_pos[i+8];\n \n \n if (v_texcoord.s>x1 && v_texcoord.s<x2 && v_texcoord.t>y1 && v_texcoord.t<y2) {\n srcTexcoord = vec2((v_texcoord.s-x1)/(x2-x1),(v_texcoord.t-y1)/(y2-y1));\n maskTexcoord = vec2(mx1+srcTexcoord.s*(mx2-mx1),my1+srcTexcoord.t*(my2-my1));\n srcColor = getSampleFromArray(srcIndex,srcTexcoord);\n maskColor = texture2D(u_image_video, maskTexcoord);\n srcColor.a = srcColor.a*(maskColor.r);\n \n bgColor = vec4(srcColor.rgb*srcColor.a,srcColor.a) + (1.0-srcColor.a)*bgColor;\n \n } \n }\n }\n ");
  1575. }
  1576. var fragmentShader = "\n precision lowp float;\n varying vec2 v_texcoord;\n varying vec2 v_alpha_texCoord;\n uniform sampler2D u_image_video;\n ".concat(sourceUniform, "\n \n void main(void) {\n vec4 bgColor = ").concat(bgColor, "\n ").concat(sourceTexure, "\n gl_FragColor = bgColor;\n }\n ");
  1577. return createShader(gl, gl.FRAGMENT_SHADER, fragmentShader);
  1578. }
  1579. }, {
  1580. key: "initTexture",
  1581. value: function initTexture() {
  1582. var gl = this.gl,
  1583. vapFrameParser = this.vapFrameParser,
  1584. textures = this.textures;
  1585. if (!vapFrameParser || !vapFrameParser.srcData) {
  1586. return;
  1587. }
  1588. var resources = vapFrameParser.srcData; // 0分配给video
  1589. var i = 1;
  1590. for (var key in resources) {
  1591. var resource = resources[key];
  1592. var texture = textures[i - 1];
  1593. if (texture) {
  1594. // 复用
  1595. gl.activeTexture(gl.TEXTURE0 + i);
  1596. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, resource.img);
  1597. } else {
  1598. this.textures.push(createTexture(gl, i, resource.img));
  1599. }
  1600. var sampler = gl.getUniformLocation(this.program, "u_image".concat(i));
  1601. gl.uniform1i(sampler, i);
  1602. this.vapFrameParser.textureMap[resource.srcId] = i++;
  1603. }
  1604. }
  1605. }, {
  1606. key: "initVideoTexture",
  1607. value: function initVideoTexture() {
  1608. var gl = this.gl,
  1609. vapFrameParser = this.vapFrameParser,
  1610. program = this.program;
  1611. if (!vapFrameParser || !vapFrameParser.config || !vapFrameParser.config.info) {
  1612. return;
  1613. } // video texture
  1614. if (!this.videoTexture) {
  1615. this.videoTexture = createTexture(gl, 0);
  1616. }
  1617. var sampler = gl.getUniformLocation(program, "u_image_video");
  1618. gl.uniform1i(sampler, 0);
  1619. gl.activeTexture(gl.TEXTURE0);
  1620. var info = vapFrameParser.config.info;
  1621. var vW = info.videoW,
  1622. vH = info.videoH;
  1623. var _info$rgbFrame = slicedToArray(info.rgbFrame, 4),
  1624. rgbX = _info$rgbFrame[0],
  1625. rgbY = _info$rgbFrame[1],
  1626. rgbW = _info$rgbFrame[2],
  1627. rgbH = _info$rgbFrame[3];
  1628. var _info$aFrame = slicedToArray(info.aFrame, 4),
  1629. aX = _info$aFrame[0],
  1630. aY = _info$aFrame[1],
  1631. aW = _info$aFrame[2],
  1632. aH = _info$aFrame[3];
  1633. var rgbCoord = computeCoord(rgbX, rgbY, rgbW, rgbH, vW, vH);
  1634. var aCoord = computeCoord(aX, aY, aW, aH, vW, vH);
  1635. var view = new Float32Array([-1, 1, rgbCoord[0], rgbCoord[3], aCoord[0], aCoord[3]].concat([1, 1, rgbCoord[1], rgbCoord[3], aCoord[1], aCoord[3]], [-1, -1, rgbCoord[0], rgbCoord[2], aCoord[0], aCoord[2]], [1, -1, rgbCoord[1], rgbCoord[2], aCoord[1], aCoord[2]]));
  1636. if (!this.vertexBuffer) {
  1637. this.vertexBuffer = gl.createBuffer();
  1638. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  1639. }
  1640. gl.bufferData(gl.ARRAY_BUFFER, view, gl.STATIC_DRAW); // 将缓冲区对象分配给a_position变量、a_texCoord变量
  1641. var size = view.BYTES_PER_ELEMENT;
  1642. var aPosition = gl.getAttribLocation(program, 'a_position');
  1643. gl.enableVertexAttribArray(aPosition);
  1644. gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, size * 6, 0); // 顶点着色器位置
  1645. var aTexCoord = gl.getAttribLocation(program, 'a_texCoord');
  1646. gl.enableVertexAttribArray(aTexCoord);
  1647. gl.vertexAttribPointer(aTexCoord, 2, gl.FLOAT, false, size * 6, size * 2); // rgb像素位置
  1648. var aAlphaTexCoord = gl.getAttribLocation(program, 'a_alpha_texCoord');
  1649. gl.enableVertexAttribArray(aAlphaTexCoord);
  1650. gl.vertexAttribPointer(aAlphaTexCoord, 2, gl.FLOAT, false, size * 6, size * 4); // rgb像素位置
  1651. }
  1652. }, {
  1653. key: "drawFrame",
  1654. value: function drawFrame(_, info) {
  1655. var gl = this.gl,
  1656. vapFrameParser = this.vapFrameParser,
  1657. video = this.video,
  1658. options = this.options;
  1659. if (!gl) {
  1660. get(getPrototypeOf(WebglRenderVap.prototype), "drawFrame", this).call(this, _, info);
  1661. return;
  1662. }
  1663. var frame = !options.loop && (info === null || info === void 0 ? void 0 : info.presentedFrames) > 0 ? info.presentedFrames - 1 : Math.round(video.currentTime * options.fps) + options.offset; // console.info('frame:', info.presentedFrames - 1, Math.round(this.video.currentTime * this.options.fps));
  1664. var frameData = vapFrameParser.getFrame(frame);
  1665. if (frameData === null || frameData === void 0 ? void 0 : frameData.obj) {
  1666. var posArr = [];
  1667. var _vapFrameParser$confi2 = vapFrameParser.config.info,
  1668. vW = _vapFrameParser$confi2.videoW,
  1669. vH = _vapFrameParser$confi2.videoH,
  1670. rgbFrame = _vapFrameParser$confi2.rgbFrame;
  1671. frameData.obj.forEach(function (frame) {
  1672. // 有可能用户没有传入src
  1673. var imgIndex = vapFrameParser.textureMap[frame.srcId];
  1674. if (imgIndex > 0) {
  1675. posArr[posArr.length] = imgIndex; // frame坐标是最终展示坐标,这里glsl中计算使用视频坐标
  1676. var _rgbFrame = slicedToArray(rgbFrame, 2),
  1677. rgbX = _rgbFrame[0],
  1678. rgbY = _rgbFrame[1];
  1679. var _frame$frame = slicedToArray(frame.frame, 4),
  1680. x = _frame$frame[0],
  1681. y = _frame$frame[1],
  1682. w = _frame$frame[2],
  1683. h = _frame$frame[3];
  1684. var _frame$mFrame = slicedToArray(frame.mFrame, 4),
  1685. mX = _frame$mFrame[0],
  1686. mY = _frame$mFrame[1],
  1687. mW = _frame$mFrame[2],
  1688. mH = _frame$mFrame[3];
  1689. var coord = computeCoord(x + rgbX, y + rgbY, w, h, vW, vH);
  1690. var mCoord = computeCoord(mX, mY, mW, mH, vW, vH);
  1691. posArr = posArr.concat(coord).concat(mCoord);
  1692. }
  1693. });
  1694. if (posArr.length) {
  1695. this.imagePosLoc = this.imagePosLoc || gl.getUniformLocation(this.program, 'image_pos');
  1696. gl.uniform1fv(this.imagePosLoc, new Float32Array(posArr));
  1697. }
  1698. }
  1699. this.trigger('frame', frame + 1, frameData, vapFrameParser.config);
  1700. gl.clear(gl.COLOR_BUFFER_BIT);
  1701. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, video); // 指定二维纹理方式
  1702. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  1703. get(getPrototypeOf(WebglRenderVap.prototype), "drawFrame", this).call(this, _, info);
  1704. } // 清理数据,为下一次播放做准备
  1705. }, {
  1706. key: "clear",
  1707. value: function clear() {
  1708. get(getPrototypeOf(WebglRenderVap.prototype), "clear", this).call(this);
  1709. var gl = this.gl; // 清除界面,解决连续播放时,第一帧是上一个mp4最后一帧的问题
  1710. gl.clear(gl.COLOR_BUFFER_BIT);
  1711. } // 销毁,释放webgl资源,销毁后调用play,资源会重新初始化
  1712. }, {
  1713. key: "destroy",
  1714. value: function destroy() {
  1715. get(getPrototypeOf(WebglRenderVap.prototype), "destroy", this).call(this);
  1716. var canvas = this.canvas,
  1717. gl = this.gl,
  1718. vertexShader = this.vertexShader,
  1719. fragmentShader = this.fragmentShader,
  1720. program = this.program,
  1721. textures = this.textures,
  1722. videoTexture = this.videoTexture,
  1723. vertexBuffer = this.vertexBuffer;
  1724. if (canvas) {
  1725. canvas.parentNode && canvas.parentNode.removeChild(canvas);
  1726. this.canvas = null;
  1727. }
  1728. if (gl) {
  1729. cleanWebGL(gl, {
  1730. program: program,
  1731. shaders: [vertexShader, fragmentShader],
  1732. textures: [].concat(toConsumableArray(textures), [videoTexture]),
  1733. buffers: [vertexBuffer]
  1734. });
  1735. }
  1736. this.gl = null;
  1737. this.vertexShader = null;
  1738. this.fragmentShader = null;
  1739. this.program = null;
  1740. this.imagePosLoc = null;
  1741. this.vertexBuffer = null;
  1742. this.videoTexture = null;
  1743. this.textures = [];
  1744. }
  1745. }]);
  1746. return WebglRenderVap;
  1747. }(VapVideo);
  1748. var isCanWebGL;
  1749. /**
  1750. * @param options
  1751. * @constructor
  1752. * @return {null}
  1753. */
  1754. function index (options) {
  1755. if (canWebGL()) {
  1756. return new WebglRenderVap(options);
  1757. } else {
  1758. throw new Error('your browser not support webgl');
  1759. }
  1760. }
  1761. function canWebGL() {
  1762. if (typeof isCanWebGL !== 'undefined') {
  1763. return isCanWebGL;
  1764. }
  1765. try {
  1766. // @ts-ignore
  1767. if (!window.WebGLRenderingContext) {
  1768. return false;
  1769. }
  1770. var canvas = document.createElement('canvas');
  1771. var context = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
  1772. isCanWebGL = !!context;
  1773. context = null;
  1774. } catch (err) {
  1775. isCanWebGL = false;
  1776. }
  1777. return isCanWebGL;
  1778. }
  1779. exports.canWebGL = canWebGL;
  1780. exports.default = index;
  1781. Object.defineProperty(exports, '__esModule', { value: true });
  1782. })));