vap.js 73 KB

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