vap.js 71 KB

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